简体   繁体   中英

Task.Wait(timeout) and exceptions

Suppose I have the following code which returns an HttpWebResponse given an HttpWebRequest:

HttpWebRequest request = ...; 
Task<WebResponse> task = Task<WebResponse>.Factory
                                          .FromAsync(
                                                request.BeginGetResponse
                                              , request.EndGetResponse
                                              , null
                                              , TaskCreationOptions.None
                                          );
if (task.Wait(TimeSpan.FromSeconds(200)))
{
    // Ok, request completed, return the response
    return task.Result;
}
else
{
    throw new WebException("GetResponse timed out", new TimeoutException());
    // is it possible that we end with an unobserved exception? I.e., 
    // what if BeginGetResponse/EndGetResponse throws
    // immediately after task.Wait has returned false?
}

What happens if the web request fails immediately after the task has timed out and has returned false? Will the task consider it an "unobserved" exception, to be thrown when its finalizer runs?

Note that the caller of this code is prepared to handle any exceptions which might be thrown before the task finishes.

Yes, the error is unobserved. The fact that you once waited does not indicate to TPL that you observed the error.

Attach a continuation that will observe the error in all cases.

task.ContinueWith(t =>     
{
    var dummy = t.Exception;
},  TaskContinuationOptions.OnlyOnFaulted 
  | TaskContinuationOptions.ExecuteSynchronously);

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