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! :)
ContinueWith(Action<Task>)Creates a continuation that executes asynchronously when the target Task completes.
The ContinueWith function is a method available on the task that allows executing code after the task has finished execution. In simple words it allows continuation. Things to note here is that ContinueWith also returns one Task. That means you can attach ContinueWith one task returned by this method.
All members of TaskCompletionSource<TResult> are thread-safe and may be used from multiple threads concurrently.
A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.
Yes this should be fine, ContinueWith checks if the previous task completed or not, if so it will immediately queue up the continuation.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With