2

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.

svick
  • 236,525
  • 50
  • 385
  • 514
Sami
  • 570
  • 1
  • 4
  • 11
  • 3
    why don't you try it? :) – Noctis Aug 06 '14 at 21:12
  • 1
    You can use ContinueWith when throws the exception and return as nothing happens. – Fals Aug 06 '14 at 21:15
  • On a bit more serious note, here's another (similar) [question on SO](http://stackoverflow.com/q/7111115/1698987). – Noctis Aug 06 '14 at 21:22
  • 1
    I did try. I didn't get an exception from the finalizer. But that is hardly a conclusive proof. Neither is stackoverflow, but any insight would be appreciated. I also know that I can use a continuation to handle the exception, but the question is, do I need to? – Sami Aug 06 '14 at 21:23

1 Answers1

3

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);
Noctis
  • 11,507
  • 3
  • 43
  • 82
usr
  • 168,620
  • 35
  • 240
  • 369