Is it possible to return from the asynchronous method before the final wait?

I have a webpage (aspx) that calls the async method in a class. The async method looks something like this:

public async Task<MyThing> GetMyThing()
{
    MyThing thing = new MyThing();
    var stuff = await Repository.GetStuff();
    // apply stuff to thing.

    var morestuff = await Repository.GetMoreStuff();
    // apply more stuff to thing.

    if (someCondition)
    {
        return thing;
    }

    var yetMoreStuff = await Repository.GetYetMoreStuff();
    // apply yet more stuff

    return thing;
}

If the condition is met, I do not need data from the last repository call. Is it expected to return before the final wait to cause me problems?

The reason I ask, I get this error in the server application log, and I'm looking for the reasons ...

Application: w3wp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.NullReferenceException
   at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean)
   at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(System.Threading.SendOrPostCallback, System.Object)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallback(System.Threading.SendOrPostCallback, System.Object)
   at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(System.Threading.ContextCallback, System.Object, System.Threading.Tasks.Task ByRef)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
+4
source share
1 answer

Yes, it’s perfectly normal not to run certain async operations. Are you OK. What would not be so good:

var notYetAwaited = DoSomethingAsync();

if (done) return "yay!";

await notYetAwaited;

i.e. a asyncwhich covers the return. This has less obvious and predictable behavior, especially in environments with a synchronous context.

- . , NRE, , sync-context.

+7

Source: https://habr.com/ru/post/1690449/


All Articles