After Task.IsCompleted what is better: await or Result [duplicate]

天涯浪子 提交于 2019-12-13 09:06:29

问题


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

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