C# 5 introduces the async/await keyword to simplify the asynchronous programming model and toss the syntax sugar to the Task + state machine of the Net4.0. In fact, the use of Task is quite simple in dealing with asynchronous programming, but now that we have introduced the new syntax sugar, we will try it, but in use, it is not so simple. The following is a summary of the actual application process of ASP.NET application, including exception capture, deadlock and application crash.

async exception capture method has three types: void, Task return method, Task

async void

the statement is unable to use catch exception, so the following code try, catch did what the egg.

 private static async void ThrowExceptionAsync (await) {Task.Delay (1000); throw new Exception ("throw an exception.");} public static async void CatchAsyncVoidException (try) {{ThrowExceptionAsync} (); catch (Exception Ex) {throw ex}; 

async Task or async Task

}

two a statement of the abnormal information will contain the Task attribute, but only need to use await in try to wait.

 private static async Task ThrowExceptionAsync (await) {Task.Delay (1000); throw new Exception ("throw an exception.");} public static async Task CatchAsyncTaskException (try) {{await} (ThrowExceptionAsync); catch (Exception Ex) {throw ex;}} TaskScheduler.UnobservedTaskException

Task anomaly information not captured by setting the global TaskScheduler.UnobservedTaskException to record the error log, add the following code in Global.asax:

 void Application_Start (object sender, EventArgs E) {/ / when the application starts running code TaskScheduler.UnobservedTaskException + = TaskScheduler_UnobservedTaskExceptionException;} void TaskScheduler_UnobservedTaskExceptionException (object sender, Unob ServedTaskExceptionEventArgs E) {if (e.Exception! = null) {something} / / do}

asynchronous programming synchronization context must be on the use of thread, the thread has a concept of synchronous context, personally think that the thread synchronization context is the most worrisome problem encountered async/await. In the existing project development, we may want to try to use async/await, but the old code is synchronous. If we call a async declaration method, the problem of deadlock and application crashes can happen accidentally.

note: the console program and the.Net Core program will not encounter this problem, and they do not need to synchronize the context.

 private static async Task lock (XXXAsync await) {Task.Delay (1000); / / some code public void (Test)} static {var = XXXAsync (task); task.Wait (}

); the code above is the perfect realization of the deadlock. By default, when Wait () is unfinished Task, the current thread context is captured and the execution of the context recovery method is used when the Task is completed. When the await execution in the async method is completed, it will try to get the rest part of the context execution method of the caller thread, but the context already contains a thread, which is waiting for the async method to finish. Then they wait for each other, and then they don't, and they die there.

for solving deadlock problem is to increase the ConfigureAwait (false)

 / / await Task.Delay (1000); await Task.Delay (1000).ConfigureAwait (false); / / 

await to solve the deadlock when waiting for the completion of the remaining part, it will try to execute the async method in this paper on the thread pool, so it is the existence of the deadlock. The

application crash

test environment always finds that the IIS application pool is always crashing, and what is the reason for it? We were on this issue is very ignorant of force, code did not seem obvious what problems, trying to deceive ourselves should be the environment itself is the problem, but the fact is indeed in the code below the poison. Through a variety of data access and testing, it can be concluded that synchronous code calls asynchronous code and the synchronization context causes problems.

is called if a async method is called. If the await is waiting, the current thread is immediately released from the return line pool, and the thread's context information is saved. If there is no way to use await (async void method, there is no way to use await), after calling the async method, the code will continue to execute. After the execution is completed, the thread is released at the current thread pool, and the thread context information will not be saved. When the asynchronous task in async implementation is completed, will get a thread from the thread pool to continue the implementation of the remaining code, at the same time will obtain contextual information when the caller thread (if the caller thread does not release loop thread pool, context information can get to). So the question is, if the caller does not use await and the thread releases the loop thread pool, because there is no context information is kept down, will not obtain, this time will throw an exception object reference not set to an instance of an object, after testing the abnormal information does not always occur, the relevant reasons and the thread release, where the caller thread context information there is no exception. The exception error information is as follows, and this exception will eventually cause the application set to stop.

 System.Web.ThreadContext.AssociateWithCurrentThread (Boolean setImpersonationContext) in System.Web.HttpApplication.OnThreadEnterPrivate (Boolean setImpersonationContext) in System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock (SendOrPostCallback callback, Object state) in System.Web.LegacyAspNetSynchronizationContext.CallCallback (SendOrPostCallback callback, Object state) in System.Web.LegacyAspNetSynchronizationContext.Post (SendOrPostCallback callback, Object state) in System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.PostAction (Object state) in System.Threading.Tasks.AwaitTaskContinuation.RunCallback (ContextCallback callback, Object state, Task& currentTask). A position in the exception stack trace at the end - raised in the System.Threading.Tasks.AwaitTaskContinuation.< > c.< ThrowAsyncIfNecessary> b__18_0 (Object s) in System.Threading.QueueUserWorkItemCallback.WaitCallback_Context (Object state) in System.Threading.ExecutionContext.RunInternal (ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) in System.Threading.ExecutionContext.Run (ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) in System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem (System.Threading.ThreadPoolWorkQueue.Dispatch) in System.Threading._ThreadPoolWaitCallback (in) What way can.PerformWaitCallback () 

be solved for the above exception? Is ConfigureAwait (false), ConfigureAwait Task (false), with this setting when the asynchronous task in async is completed, do not read the context information when calling it the original thread, the remaining part of the performance of the async method but in the context of the thread pool.

 public static Task (XXXAsync) {await (Task.Run) (=> code} {/ / some).ConfigureAwait (false);}

"summarized above is Xiaobian to introduce the ASP.NET with async/await, I hope to help you, if you have any questions please give me a message, Xiao Bian will reply you timely. Thank you for your support for the home website of the script!


This concludes the body part