问题描述
在 TaskCompletionSource.Task
上使用 ContinueWith(...)
方法是否安全,如果 TaskCompletionSource.SetResult(...)
已被调用?
Is it safe to use the ContinueWith(...)
method on a TaskCompletionSource.Task
if the TaskCompletionSource.SetResult(...)
has already been called?
该基本代码有望帮助解决这个问题:
This basic code will hopefully help to frame the question:
// 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(...)
.设置吗?
Will the Console.WriteLine(...)
execute if the WebClient.DownloadStringCompleted
event has already fired before the task.ContinueWith
is set?
MSDN这样说( Task.ContinueWith ):
MSDN has this to say (Task.ContinueWith):
返回的任务要等到当前任务已完成,是否由于运行到成功完成,由于未处理的异常而导致的错误,或由于被取消而提前退出.
The returned Task will not be scheduled for execution until thecurrent task has completed, whether it completes due to running tocompletion successfully, faulting due to an unhandled exception, orexiting out early due to being canceled.
不幸的是,这没有提到如果调用此方法并且任务已经完成,会发生什么情况.
Unfortunately that doesn't mention what happens if this method is called and the task has already completed.
在此先感谢您提供的任何信息!:)
Thank you in advance for any information you can provide! :)
推荐答案
是的,没关系,ContinueWith检查上一个任务是否完成,如果这样,它将立即排队继续执行.
Yes this should be fine, ContinueWith checks if the previous task completed or not, if so it will immediately queue up the continuation.
这篇关于在TaskCompletionSource.Task(调用了.SetResult)上调用ContinueWith方法是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!