假设我有以下代码,在给定HttpWebRequest的情况下返回HttpWebResponse:
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?
}
如果Web请求在任务超时后立即失败并返回false,会发生什么?该任务是否会将其视为“未观察到的”异常,在其终结器运行时抛出?
请注意,此代码的调用者已准备好处理在任务完成之前可能抛出的任何异常。
答案 0 :(得分:3)
是的,错误未被观察到。您曾经等待的事实并未向TPL表明您发现了错误。
附加一个在所有情况下都会观察到错误的延续。
task.ContinueWith(t =>
{
var dummy = t.Exception;
}, TaskContinuationOptions.OnlyOnFaulted
| TaskContinuationOptions.ExecuteSynchronously);