async await Task null reference exception

泪湿孤枕 提交于 2019-12-02 14:53:06

问题


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.

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!


回答1:


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)



来源:https://stackoverflow.com/questions/39021872/async-await-task-null-reference-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!