当前位置:网站首页>C asynchronous programming (async and await) and asynchronous method synchronous invocation
C asynchronous programming (async and await) and asynchronous method synchronous invocation
2022-06-12 04:42:00 【Wind god Shura envoy】
1、 What is asynchronous ?
Asynchronous operations are often used to perform tasks that may take a long time to complete , If you open a large file 、 Connect to a remote computer or query a database = Asynchronous operations are performed in threads other than the main application thread . When an application calls a method to perform an operation asynchronously , An application can continue executing while an asynchronous method performs its task .
2、 The difference between synchronous and asynchronous
Sync (Synchronous): When performing an operation , The application must wait for the operation to complete before proceeding .
asynchronous (Asynchronous): When performing an operation , The application can continue executing while the asynchronous operation is executing . The essence : Asynchronous operations , Started a new thread , The main thread executes in parallel with the method thread .
3、 The difference between asynchronous and multithreading
We already know , Asynchronous and multithreading are not the same thing , Asynchrony is the ultimate goal , Multithreading is just a means for us to realize asynchrony . Asynchrony is when a call request is sent to the callee , Instead of waiting for the result to return, the caller can do something else . Asynchrony can be implemented by multithreading or by other processes .
Simply put : Asynchronous threads are managed by the thread pool , And multithreading , We can control ourselves , Of course, we can also use thread pool in multithreading .
Take the Internet pickpocket , If you use asynchronous mode to implement , It uses thread pools for management . When an asynchronous operation is executed , It will throw the operation to a worker thread in the thread pool to complete . When it starts I/O During operation , Asynchrony returns the worker thread to the thread pool , This means that the job of getting the web page no longer takes up any CPU Resources . Until asynchronous completion , That is, the web page is obtained , Asynchronous will notify the thread pool through callback . so , Asynchronous mode relies on thread pools , Greatly saved CPU Resources for .
notes :DMA(Direct Memory Access) Direct memory access , seeing the name of a thing one thinks of its function DMA The function is to allow the device to bypass the processor , Read data directly from memory . Data exchange through direct memory access can be virtually lossless CPU Resources for . In hardware , Hard disk 、 network card 、 Sound card 、 Graphics cards have direct memory access . The asynchronous programming model allows us to make full use of the hardware's direct memory access function to release CPU The pressure of the .
The application scenarios of the two :
- Computing intensive work , Using multithreading .
- IO Intensive work , Asynchronous mechanism is adopted .
C# Asynchronous code reference (async and await)
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncAwaitDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("main start..");
AsyncMethod();
Thread.Sleep(1000);
Console.WriteLine("main end..");
Console.ReadLine();
}
static async void AsyncMethod()
{
Console.WriteLine("start async");
var result = await MyMethod();
Console.WriteLine("end async");
//return 1;
}
static async Task<int> MyMethod()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Async start:" + i.ToString() + "..");
await Task.Delay(1000); // Simulation time operation
}
return 0;
}
}
}
Use Wait() and GetAwaiter().GetResult() Method to implement synchronous execution of asynchronous methods
using System;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Async Test job:");
Console.WriteLine("main start..");
Console.WriteLine("MyMethod() Asynchronous methods execute synchronously :");
MyMethod().Wait();// stay main Waiting in the async Method execution complete
int i = MyMethod().GetAwaiter().GetResult();// Used in main Get in sync async method
Console.WriteLine("i:" + i);
Console.WriteLine("main end..");
Console.ReadKey(true);
}
static async Task<int> MyMethod()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Async start:" + i.ToString() + "..");
await Task.Delay(1000); // Simulation time operation
}
return 0;
}
}
}
C# Asynchronous programming Asynchronous delegates call synchronous methods
Synchronization operation :
It consists of successive component or function calls . A synchronization call will block the entire process until this operation is completed .
Asynchronous operation :
The calling thread that starts the operation will not be blocked . The calling program must pass the rotation detection 、 Interrupt signals in software or simply wait for the completion signal to find the completion of the call .
.NET Two design patterns are provided for asynchronous operation :
- Use
IAsyncResultAsynchronous operation of objects . - Asynchronous operations using events .
.NET Asynchronous programming is supported in many aspects of , These include :
- file IO、 flow IO、 Socket IO.
- The Internet .
- Remote processing channel (HTTP、TCP) And the agent .
- Use ASP.NET Created
XML Web services. - ASP.NET Web forms .
- Use
MessageQueueClass .
Asynchronous delegates provide the ability to call synchronous methods asynchronously .
- When a delegate is invoked synchronously , The calling method directly calls the target method on the current thread . If the compiler supports asynchronous delegation , Then it will generate the calling method and
BeginInvokeandEndInvokeMethod . - If the
BeginInvokeMethod , Then the common language runtime will queue the request and immediately return it to the caller . The target method will be called on the thread from the thread pool . The original thread submitting the request is free to continue executing in parallel with the target method , The target method is run on thread pool threads - In the callback , Use
EndInvokeMethod to get the return value and input / Output parameters . If there is no rightBeginInvokeSpecify callback , Can be used on the original thread that submitted the requestEndInvoke.
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace ClassMain
{
// Statement of entrustment ( Function signature )
delegate string MyMethodDelegate();
class MyClass
{
// The dynamic method to call
public string MyMethod1()
{
return "Hello Word1";
}
// The static method to call
public static string MyMethod2()
{
return "Hello Word2";
}
}
class Class1
{
/// <summary>
/// The main entry point for the application .
/// </summary>
[STAThread]
static void Main(string[] args)
{
MyClass myClass = new MyClass();
// The way 1: Declaration delegation , call MyMethod1
MyMethodDelegate d = new MyMethodDelegate(myClass.MyMethod1);
string strEnd = d();
Console.WriteLine(strEnd);
// The way 2: Declaration delegation , call MyMethod2 ( Use AsyncResult Object call )
d = new MyMethodDelegate(MyClass.MyMethod2); // Define a delegate that can be used by multiple methods
AsyncResult myResult; // This class encloses the result of an asynchronous invocation of an asynchronous delegate , adopt AsyncResult Get the results .
myResult = (AsyncResult)d.BeginInvoke(null, null); // Start calling
while (!myResult.IsCompleted) // Determine whether the thread has completed execution
{
Console.WriteLine(" Executing asynchronously MyMethod2 .....");
}
Console.WriteLine(" Method MyMethod2 Execution completed !");
strEnd = d.EndInvoke(myResult); // Wait for the method called by the delegate to complete , And return the result
Console.WriteLine(strEnd);
Console.Read();
}
}
}
边栏推荐
- Install/Remove of the Service Denied!
- 2022 low voltage electrician test questions and simulation test
- What are the black box test case design methods in software testing methods?
- Sqel easy to use
- mysqld: Can‘t create directory ‘D: oftinstall\mysql57 (Errcode: 2 - No such file or directory)
- L1-068 harmonic average (10 points)
- Data processing and data set preparation
- Bearpi IOT serial port transceiver 1- normal mode
- Operation of simulated examination platform for 2022 safety officer-b certificate examination questions
- Jwt Learning and use
猜你喜欢

Image processing 13- calculation of integral diagram

kali_ Nat mode, bridging Internet / host only_ detailed

QT compiling security video monitoring system 43- picture playback

疫情数据分析平台工作报告【2】接口API

Function realization and application of trait

Tasks in C #

22-2-28 there are many things to do at work today, ETH analysis

How to use union all in LINQ- How to use union all in LINQ?

Operation of simulated examination platform for theoretical question bank of G2 utility boiler stoker in 2022

存储器的保护
随机推荐
分布式锁介绍
ShanMeng and Beijing Adoption Day start NFT digital collection public offering
Let me tell you the benefits of code refactoring
疫情数据分析平台工作报告【1】数据采集
SqEL简单上手
Zabbix6.0新功能Geomap 地图标记 你会用吗?
leetcode 205. Isomorphic Strings
Kill session? This cross domain authentication solution is really elegant!
L1-065 "nonsense code" (5 points)
leetcode797. All possible paths (medium)
@What happens if bean and @component are used on the same class?
Bearpi IOT lighting LED
Some points needing attention about thread pool
one billion one hundred and eleven million one hundred and eleven thousand one hundred and eleven
C# Task. Waitall method
Jwt Learning and use
What is reverse repurchase of treasury bonds? Is the reverse repurchase of treasury bonds safe?
Sqel easy to use
SQL注入上传一句话木马(转)
kali_ Nat mode, bridging Internet / host only_ detailed