[英]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.