繁体   English   中英

可以在最终等待之前从异步方法返回吗?

[英]Is it OK to return from an async method before the final await?

我有一个在类中调用异步方法的网页(aspx)。 async方法看起来像这样:

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;
}

如果满足条件,我不需要上次存储库调用的数据。 最终等待之前的回报是否会引起我的问​​题?

我问的原因是我在服务器应用程序日志中收到此错误,我正在寻找原因...

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()

是的,不运行某些异步操作完全没问题。 你有什么好。 什么不会那么好会是:

var notYetAwaited = DoSomethingAsync();

if (done) return "yay!";

await notYetAwaited;

即跨越返回的async操作。 这具有不太明显和可预测的行为,尤其是在同步环境环境中。

你的问题不太可能是因为回归。 听起来这只是在您的数据代码中发生的NRE,它正在sync-context回调中浮出水面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM