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!
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