Is it safe to call the ContinueWith method on a Ta

2019-04-03 13:53发布

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

Will the Console.WriteLine(...) execute if the WebClient.DownloadStringCompleted event has already fired before the task.ContinueWith is set?

MSDN has this to say (Task.ContinueWith):

Task.ContinueWith Method

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! :)

2条回答
Root(大扎)
2楼-- · 2019-04-03 14:29

If the specified task has already completed by the time ContinueWith is called, the synchronous continuation will run on the thread calling ContinueWith. https://msdn.microsoft.com/en-us/library/dd321576(v=vs.110).aspx

查看更多
【Aperson】
3楼-- · 2019-04-03 14:31

Yes this should be fine, ContinueWith checks if the previous task completed or not, if so it will immediately queue up the continuation.

查看更多
登录 后发表回答