The ASP: Synchronous method calls the Async method to throw the net application crash

Source: Internet
Author: User
Tags stack trace

It is only known if the asynchronous (async) method is called in the synchronous method. Result waits for the result to be called, causing thread deadlock (deadlock). I have also eaten this suffering, see wait until the flowers also thanked the await.

An accidental situation yesterday caused the Async method to be called in a synchronous method and was not used. result, resulting in the crash of the entire ASP. NET application, the experience of synchronous/asynchronous fire and fire difficult.

This was the case with the release of an asynchronous ASP. NET program, which has a synchronous method:

 Public Static void Notify (stringstringint  recipientid) {    //...}

is transformed into an async method:

 Public Static Async Task Notify (stringstringint  recipientid) {    //await ...}

It was previously called synchronously in WebForms (. aspx):

<script runat="server">    void  Page_Load (Object sender, EventArgs E )    {        //...         msgservice.notify (title, body, userId);         // ...     }</script>

Now call it asynchronously in the MVC Controller action:

 Public class applycontroller:controller{    [HttpPost]    publicasync task<string > Pass ()    {        //...        await msgservice.notify (title, body, userId);         // ...     }}

This release is intended to replace WebForms with MVC, but the. aspx file that was released synchronously when the Notify () method was called is not removed from the server.

After publishing, the ASP will crash (crash) for a few minutes, as follows:

A) A 503 error occurred while visiting the website;

b) The IIS Manager displays the corresponding application pool in the stopped state;

c) The following three errors were found in the Windows event log:

Log 1:

An unhandled exception has occurred and the process has been terminated. Application ID:/lm/w3svc/15/rootprocess id:23808exception:system.nullreferenceexceptionmessage: Object reference not set to an instance of an object. StackTrace:
In 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 Syst Em. Threading.Tasks.AwaitTaskContinuation.RunCallback (ContextCallback callback, Object State, task& currenttask)--- Throws an exception at the end of the stack trace in the previous location---system.threading.tasks.awaittaskcontinuation.<throwasyncifnecessary>b__1 (Object s) in the 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 () in System.Threading.ThreadPoolWorkQueue.Dispatch ()

Log 2:

Application: W3wp.exeframework Version: v4.0.30319 Description: The process terminates due to an unhandled exception. Exception information: System.NullReferenceException stack:   in system.threading.tasks.awaittaskcontinuation.< Throwasyncifnecessary>b__1 (System.Object)   in System.Threading.ExecutionContext.RunInternal ( System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)   in System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)   in System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem ()   in System.Threading.ThreadPoolWorkQueue.Dispatch ()

Log 3:

Faulting application Name:w3wp.exe, version:7.5.7601.17514, time stamp:0x4ce7afa2faulting module Name:KERNELBASE.dll, version:6.1.7601.18798, Time stamp:0x5507b87aexception code:0xe0434352fault offset:0x000000000001aaadfaulting Process id:0x5d00faulting Application start time:0x01d0b86f3af9058efaulting application path:c:\windows\system32\ Inetsrv\w3wp.exefaulting Module Path:c:\windows\system32\kernelbase.dllreport Id: 7bec0e6c-2462-11e5-b24e-c43d8baaa802

From the log information, the problem must be asynchronous, so check all the code that makes the asynchronous call, not the problem (except check the. aspx file that you think is not in use, not deleted).

Then I thought of the. aspx file that was not deleted, but it has been replaced by MVC, not in use. If it is caused by it, there is only one possibility ... This file is still being accessed by some requests. After careful investigation found that the original is the reference JS place without hash parameters, causing some client browser because of the reason for the cache is still using the old version of JS, the older version of JS will also make an AJAX request to the. aspx file.

It turned out to be an oversight that caused the asynchronous method to be called directly in the synchronous method, but the curiosity was stimulated by the fact that it was so powerful that it caused the entire application to crash.

After reading some information on the Internet, I have some knowledge about this problem.

in ASP. NET (ASP. NET is inherently multithreaded, thread-pooling-based, without the concept of a UI thread), if you call an async method, if there is an await accompanying, the current line Cheng Lima is released back to the thread pool, the context information of the threads (such as Reqeust Context) is saved, and if no await accompanies (and no other wait code), after calling the Async method, the code continues to execute until it is finished, the current thread is freed back to the thread pool, and the context information for the thread is not saved. When an asynchronous task in Async completes (note: The asynchronous task is done in a state machine that is not done in another thread), it takes a thread from the thread pool to continue executing, reading the context information of the original thread that called it at the time (the behavior by default, If Configureawait (false), there is no such a step), if the original call did not use the await, the thread's context information is not saved, then the NullReferenceException will be thrown. An unhandled null reference exception that occurs at this level can cause the entire application to crash, or more precisely the process in which the application is located. Because such an exception is too dangerous, in order not to let a rat broke a pot of soup, can only be sacrificed.  

So, if you do not want to be sacrificed, either honestly await, or tell the Async method not to read the original thread's contextual information (Configureawait (false), without actual validation is valid), or the thread that calls the Async method does not need to save the context information , such as calling the Async method in Task.run (or Task.Factory.StartNew), which calls the Async method with a new thread.

"Recommended"

Best practice to call configureawait for all server-side code

Difference between the TPL & Async/await (Thread handling)

Does an async void method create a new thread everytime it is called?

The ASP: Synchronous method calls the Async method to throw the net application crash

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.