简体   繁体   中英

async await Task null reference exception

I am getting NullReferenceExceptions on a webforms project I'm maintaining. The catch is that there is no stacktrace for this exception because none of my code causes the exception. NullReferenceException 未处理

Exception details copied to the clipboard offers zero assistance:
System.NullReferenceException was unhandled Message: An unhandled exception of type 'System.NullReferenceException' occurred in mscorlib.dll Additional information: Object reference not set to an instance of an object.

When I view the non-user code stacktrace, I see the following (all in mscorlib): 堆栈跟踪

The error occurs randomly and inconsistently, either by loading pages or by postbacks. The problem began after I added System.Net.Http.HttpClient for pulling data from REST services exposed on other sites. Note that HttpClient contains only async methods for sending/receiving data. Based on the internal stacktrace, I highly suspect the Task<> / async / await as the culprit.

To assist in troubleshooting, let me reaffirm that I'm running this in a WebForms site compiling in .NET 4.6 (and if you're about to tell me my problem is that I need to upgrade to MVC, save your keystrokes and don't say it). While HttpClient exposes everything as Task<>, I am calling them synchronously by calling:
Task<MyObject> myResultTask = restClient.GetResultAsync(); MyObject myResult = myResultTask.Result; // no await

Thanks in advance!

I just had this issue and would like to suggest this as the answer.

In your web.config make sure you have the following:

  <system.Web>
      <httpRuntime targetFramework="4.5" />
  </system.Web>

and

<appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />     
</appSettings>

See more info here:

https://blogs.msdn.microsoft.com/webdev/2012/11/19/all-about-httpruntime-targetframework/

It seems to just crash randomly if you don't do this. I am a big fan of backwards compatibility but not when it just crashes if you don't opt in to the new way.

(Suggested in comment from Stephen Cleary)

这对我有用,感谢您直截了当。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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