简体   繁体   English

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

[英]Is it safe to call the ContinueWith method on a TaskCompletionSource.Task (that has had it's .SetResult called)?

Is it safe to use the ContinueWith(...) method on a TaskCompletionSource.Task if the TaskCompletionSource.SetResult(...) has already been called? 它是安全使用ContinueWith(...)上的方法TaskCompletionSource.Task如果TaskCompletionSource.SetResult(...)已经叫什么名字?

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*
}

Will the Console.WriteLine(...) execute if the WebClient.DownloadStringCompleted event has already fired before the task.ContinueWith is set? 如果在设置task.ContinueWith之前已经触发了WebClient.DownloadStringCompleted事件, Console.WriteLine(...)是否会执行?

MSDN has this to say ( Task.ContinueWith ): MSDN就是这么说的( Task.ContinueWith ):

Task.ContinueWith Method Task.ContinueWith方法

The returned Task will not be scheduled for execution until the current task has completed, whether it completes due to running to completion successfully, faulting due to an unhandled exception, or exiting 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检查前一个任务是否完成,如果是,它将立即排队继续。

If the specified task has already completed by the time ContinueWith is called, the synchronous continuation will run on the thread calling ContinueWith. 如果在调用ContinueWith时已完成指定的任务,则同步继续将在调用ContinueWith的线程上运行。 https://msdn.microsoft.com/en-us/library/dd321576(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/dd321576(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM