【发布时间】:2011-09-15 15:41:39
【问题描述】:
如果TaskCompletionSource.SetResult(...) 已经被调用,那么在TaskCompletionSource.Task 上使用ContinueWith(...) 方法是否安全?
此基本代码有望帮助解决问题:
// this was written inside the question box, please excuse any silly errors and lack of error checking (I'm not near VS right now)...
private WebClient _webClient = new WebClient();
public Task<string> GetExamplePage() {
var tcs = new TaskCompletionSource<string>();
web.DownloadStringCompleted += (s, ea) => tcs.SetResult(ea.Result);
web.DownloadStringAsync(new URI(@"http://www.example.com/example.html"));
return tcs.task;
}
public void ProcessExamplePage() {
var task = GetExamplePage();
Thread.Sleep(1000);
task.ContinueWith(t => Console.WriteLine(t.Result)); // *line in question*
}
如果WebClient.DownloadStringCompleted 事件在task.ContinueWith 设置之前已经触发,Console.WriteLine(...) 会执行吗?
MSDN 有话要说 (Task.ContinueWith):
Task.ContinueWith 方法
返回的任务将不会被安排执行,直到 当前任务已完成,是否因运行而完成 成功完成,由于未处理的异常而出错,或 由于被取消而提前退出。
不幸的是,没有提到如果调用此方法并且任务已经完成会发生什么。
提前感谢您提供的任何信息! :)
【问题讨论】:
标签: c# .net asynchronous task-parallel-library