问题
I'm working in a simple timeout code for my http requests. I got this
private async Task<HttpResponseMessage> ExecuteIOTask(Task<HttpResponseMessage> ioTask, int timeout)
{
var timeoutTask = await Task.WhenAny(Task.Delay(timeout), ioTask);
if (ioTask.IsCompleted)
return ioTask.Result;
throw new TimeoutException();
}
After IsCompleted, is there any difference using Result vs await ? The task is already completed at that instance, so I think the performance should be the same. But i'm a little concern about the exception handling. I think Result is not going to propagate the exceptions but await will.
Is this correct?
回答1:
Do not use .Result, always use await.
Please note that .Result can cause deadlocks and can cause some unpredictable behaviors in the applications.
The only way then would be to take the process dump and then analyze dump in procdump. Believe me it is going to be very difficult debugging.
Please find best practices about async programming at this blog.
As far as exception handling is concerned, it is mentioned in this blog that:
Every Task will store a list of exceptions. When you await a Task, the first exception is re-thrown, so you can catch the specific exception type (such as InvalidOperationException). However, when you synchronously block on a Task using Task.Wait or Task.Result, all of the exceptions are wrapped in an AggregateException and thrown.
Hope this helps.
来源:https://stackoverflow.com/questions/55268681/after-task-iscompleted-what-is-better-await-or-result