First of all, don't use TaskContinuationOptions.ExecuteSynchronously
for this purpose! You can't force the continuation on the same thread. It only works with very high probability. There are always cases where it does not work: Too much recursion will cause the TPL not to execute synchronously. Custom TaskScheduler
s are also not obliged to support this.
This is a common misconception, especially because it is being wrongly propagated on the web. Here is some reading on that topic: http://blogs.msdn.com/b/pfxteam/archive/2012/02/07/10265067.aspx
If you need to run on the same thread, do this:
Task.Factory.StartNew(() => { First(); Second(); });
So easy.
Let me illustrate why that works by showing an alternative solution:
void MyCompositeTask()
{
var result = First();
Second(result);
}
Task.Factory.StartNew(() => MyCompositeTask());
This looks more intuitive: We pass MyCompositeTask
to the TPL to run. The TPL does not care what we do in our callback. We can do whatever we want, including calling multiple methods and passing the results.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…