在TaskCompletionSource.Task(已经调用了.SetResult)上调用ContinueWith方法是否安全?

如果已经调用了TaskCompletionSource.SetResult(...)TaskCompletionSource.SetResult(...)上使用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 GetExamplePage() { var tcs = new TaskCompletionSource(); 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* } 

如果在设置task.ContinueWith之前已经触发了WebClient.DownloadStringCompleted事件, Console.WriteLine(...)是否会执行?

MSDN就是这么说的( Task.ContinueWith ):

Task.ContinueWith方法

返回的任务将不会被安排执行,直到当前任务完成,是否由于运行成功完成而完成,由于未处理的exception导致的故障,或由于被取消而提前退出。

不幸的是,没有提到如果调用此方法并且任务已经完成会发生什么。

提前感谢您提供的任何信息! 🙂

是的,这应该没问题,ContinueWith检查前一个任务是否完成,如果是,它会立即排队继续。

如果在调用ContinueWith时已完成指定的任务,则同步继续将在调用ContinueWith的线程上运行。 https://msdn.microsoft.com/en-us/library/dd321576(v=vs.110).aspx