Question

I just started getting familiar with Task Parallel Library and have a rather trivial question to which I was unable to find a clear answer.

Are there any difference between the following snippets and when I should choose one over the other?

Task t = Task.Factory.StartNew(() => {
    Result result = Utils.Calculate();
    Utils.ProcessResults(result);
});  

And

Task<Result> t = Task<Result>.Factory.StartNew(() =>  Utils.Calculate());
t.ContinueWith((x) =>  Utils.ProcessResults(x));

It seems like the first approach is preffereable since there is less overhead to it and actually going with ContinueWith doesn't make much sense in this simple example. But then again, I've seen second approach being used on some occasions where it could have been interchangeably replaced with the first one...

Was it helpful?

Solution

With the continuation model, you're scheduling the continuation for asynchronous processing when the original task finishes. This means that a thread could potentially pick up your original task, process it, pick up some other work, process that, and only at some later point pick up your continuation for processing.

Without a continuation, you're guaranteed that the processing thread will execute both statements before the task completes.

I admit I have limited experience with these scenarios, but a couple of reasons that jump to mind for using continuations:

  • You're scheduling other work that you want (potentially) processed before the continuation.
  • You want a way to alert the calling thread that the first statement has finished (i.e. to update some piece of UI) but don't care much that the second has finished.

OTHER TIPS

ContinueWith() is best used if you're doing some asynchronous operation that must complete before you proceed with your program logic. For example, if you're retrieving something from a database, you might put that into a task so that you don't freeze the UI. You can't just continue with the next statement since the asynchronous operation might not have completed yet, so you put the next statement in a ContinueWith(). When the async operation is done, the next statement is executed.

In your case, if Utils.Calculate() is synchronous, go for the first method. If it's asynchronous, go for the second.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top