In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces you how to achieve asynchronous programming in C#, the content is very detailed, interested friends can refer to, I hope it can be helpful to you.
The basis of asynchronous method and its running processes Async and Await
Asynchronous methods are decorated with async, which contains one or more await expressions or statements, the method runs synchronously until the first Await is reached, pauses until the waiting task completes, and after the task completes, control returns to the caller of the method. If the method does not contain an await, the method is not suspended like a synchronous method.
Asynchronous methods usually contain one or more instances of the await operator, but the lack of an await expression does not cause a compiler error to be generated, which warns because there is no await, but the compilation still passes.
The asynchronous method uses the await keyword to determine the wait location, but the await expression does not block the thread that is executing to this location, which means that the asynchronous method simply pauses while the await expression is executing, does not cause the method to exit, but only causes the finally code block to not run. The asynchronous method can pass through that location and continue to execute the rest of the logic only after the waiting task is completed, where control is returned to the caller of the asynchronous method.
If the asynchronous method does not mark the pause point with the Await operator, the asynchronous method executes as a synchronous method, even if there is an Async modifier. Such as the following example
1: public async static Task GetUserInfoAsync () 2: {3: User user = await db.User.FirstOrDefaultAsync (); / / 4: 5: Task user = db.User.FirstOrDefaultAsync () will be suspended here. Note that the return value has also changed. Next, we will discuss the return value of the asynchronous method 6: 7: return string.Empty; 8:}
With a MSDN description, the aysnc keyword is an unreserved keyword. It is a keyword when decorating a method or lambda expression, and await also exists as a keyword. In all other contexts, async and await interpret it as an identifier. However, developers can not pay too much attention to this section, just need to know that aysnc will identify a method as an asynchronous method, while await can suspend the execution of asynchronous methods.
Key points
1. Unlike the method modified by async, if the method contains the await keyword, the method must use the async identifier, otherwise the compilation will not pass.
2. In asynchronous programming, it is recommended that an asynchronous method marked with the async keyword should contain at least one await expression or statement.
3. The naming of asynchronous methods ends with Async.
Asynchronous return type and exception handling
It is important to note that the asynchronous approach discussed in this article refers to the task-based asynchronous programming model, and the return value is Task or Task.
1. If the method needs to return a string type, it will return Task. If the method does not specify a return type, it returns Task. Each returned task represents work in progress, which encapsulates information about the status of the asynchronous process, and throws an exception if it does not succeed. The asynchronous method returns Task or Task. The properties of the returned task carry information about its status and history, such as whether the task completed, whether the asynchronous method caused an exception or cancelled, and what the end result is. You can access these properties using the await operator.
1: public async static Task GetUserInfoAsync () 2: {3: User user = await db.User.FirstOrDefautAsync (); 4: 5: return user; 6:}
2. If the waiting task returns an asynchronous method that causes an exception, the await operator throws an exception synchronously. If the asynchronous method of the waiting return task is cancelled, the await operator throws an OperationCanceledException. If await blocking is not used in asynchronous methods, you can use try-catch to catch exceptions, but the timing of the exception may be delayed.
The running process of asynchronous method
To understand the operation mechanism of asynchronous methods is to understand how the control flow in asynchronous programming is executed step by step. If you need to learn more about the control flow, you can check it asynchronously in MSDN.
The following figure and its description are extracted from MSDN:
The values in the diagram correspond to the following steps.
The event handler calls and waits for the AccessTheWebAsync asynchronous method.
AccessTheWebAsync creates a HttpClient instance and calls the GetStringAsync asynchronous method, which is returned as a string of acquired contents.
Something has happened in GetStringAsync that suspends its progress. You may have to wait for other blocking tasks to complete. To avoid blocking resources, GetStringAsync transfers control to its caller, AccessTheWebAsync. GetStringAsync returns Task, where TResult is a string and AccessTheWebAsync assigns the task to the getStringTask variable. This task invokes the process that GetStringAsync is in progress and generates a return string to urlcontent when the call is completed.
Since you have not yet waited for the getStringTask, the AccessTheWebAsync can continue to execute without relying on the completion of the GetStringAsync final result. The task continues to call the synchronization method DoIndependentWork.
DoIndependentWork, as a synchronization method, returns to the caller after its own work is done.
AccessTheWebAsync has finished running and can be unaffected by the results of getStringTask. Next, AccessTheWebAsync needs to calculate and return the length of the downloaded string, but this method can only calculate this value if the string is obtained.
Therefore, AccessTheWebAsync uses an await operator to suspend its task and gives control to the event handler that calls AccessTheWebAsync. AccessTheWebAsync returns the Task to the caller. This task calculates the length of the download string.
GetStringAsync completes and generates a string result. The string result is not returned by calling GetStringAsync in the way you expect. Remember, this method has returned one of the tasks in step 3. Instead, the string result is stored in the task that represents the completion of the getStringTask method. The await operator retrieves the results from getStringTask. The assignment statement assigns the retrieved result to urlContents.
This method calculates the length of the string when AccessTheWebAsync gets the result of the string. Then, the AccessTheWebAsync work will also be completed and wait for the event handler to continue to be used. The event handler will also eventually get the length information of the string.
Note:
If the GetStringAsync (and therefore getStringTask) completes before the AccessTheWebAsync waits, the control remains in the AccessTheWebAsync. If the asynchronous invocation procedure (AccessTheWebAsync) is completed and the AccessTheWebSync does not have to wait for the final result, suspending and returning to getStringTask would be a waste of resources.
Within the caller (the event handler in this example), the processing mode continues. Before waiting for the result, the caller can do other work that does not depend on the AccessTheWebAsync result, otherwise it will have to wait a while. Event handlers wait for AccessTheWebAsync, while AccessTheWebAsync waits for GetStringAsync.
The influence of Asynchronous programming on performance
In .NET asynchronous programming, async and await do not create other threads, and asynchronous methods do not run on their own threads, so it does not require multithreading. Only when the method is active, the method runs in the current synchronization context and uses the time on the thread. You can use Task.Run to move work that takes up a lot of CPU to background threads, but background threads do not help processes that are waiting for results to become available.
For asynchronous programming, the asynchronous-based approach is superior to the existing methods in almost every use case. Specifically, this approach is better than BackgroundWorker's I _ map O binding operation because the code is simpler and there is no need to prevent race conditions. When used in conjunction with Task.Run, asynchronous programming is more suitable for CPU binding operations than BackgroundWorker, because asynchronous programming distinguishes the coordination details of running code from the work of Task.Run transferring to thread pools.
So what is the impact of asynchronous programming on threads? compared to everyone should know, there are two types of threads in ASP.NET, worker threads and IO threads.
The worker thread that handles ordinary requests is also the thread we use most. This thread is limited and is related to the number of root CPU. IO threads, such as file reading and writing, network operations, etc., can be implemented asynchronously and improve performance. The Iswap O thread is usually idle. Therefore, IO thread can be used instead of worker thread. On the one hand, it makes full use of system resources, on the other hand, it saves the loss caused by worker thread scheduling and switching.
From this we need to understand that the use of asynchrony can lead to great improvements in Istroke O-intensive processing, such as database operations and network operations.
Even if asynchronous programming brings performance improvement, careless use will have an adverse effect on system performance, such as asynchronous programming brought about by the direct use of Task.Run or Task.Factory.StartNew, which will take up the switching between worker threads and worker threads.
What should be paid attention to in asynchronous programming?
1. At the same time, async and await are very intrusive or transitive, and all calls need to use async and await simultaneously, which has a great impact on the modification of the old code in the system.
2. Lock locks cannot be used in asynchronous programming, because asynchronous methods do not run on their own threads, making lock redundant. However, in asynchronous programming scenarios, AsyncLock locks can be used to lock the corresponding code.
3. In asynchronous programming, the recommended way is to avoid the continuation of the online text. I will not explain it any more here. Refer to my previous article, "Asynchronous programming (1)".
4. Whether asynchronous programming has really improved the performance of the system is improved in most scenarios, especially in business scenarios where IWeiO operations are more intensive, such as querying databases and network calls.
On how to achieve asynchronous programming in C# to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.