Continuation Task在与先前相同的线程中 [英] Continuation Task in the same thread as previous

查看:236
本文介绍了Continuation Task在与先前相同的线程中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WebService,它创建一个任务和一个延续任务.

I have an WebService that creates a task and a continuation task.

在第一个任务中,我们设置 Thread.CurrentPrincipal

In the first task we set Thread.CurrentPrincipal

因此,当ContinuationTask启动时,它不再具有Thread.CurrentPrincipal.

Hence, When the ContinuationTask starts it no longer has the Thread.CurrentPrincipal.

我想在 ContinuationTask 中指定它应与它的前一个线程相同运行.

I'd like to specify in the ContinuationTask that it should run in the same thread as its antecedent.

我已经在网上搜索了,但是我只发现了在SynchronizationContext中运行线程的要求,因此我开始认为我缺少一些基本规则,特别是关于Thread.Principal应该如何工作.

I've searched the web but i only found the requirement for the thread to run in the SynchronizationContext, therefore i am starting to think I am missing some basic rule, specially regarding how Thread.Principal should work.

推荐答案

首先,请勿为此目的使用TaskContinuationOptions.ExecuteSynchronously!您不能在同一线程上强制继续执行.它只能以很高的概率工作.在某些情况下,它不起作用:过多的递归将导致TPL无法同步执行.自定义TaskScheduler也不是必须支持的.

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 TaskSchedulers are also not obliged to support this.

这是一个常见的误解,尤其是因为它是在网络上错误传播的.这是有关该主题的一些阅读材料: http://blogs .msdn.com/b/pfxteam/archive/2012/02/07/10265067.aspx

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(); });

太简单了.

让我通过显示替代解决方案来说明其工作原理:

Let me illustrate why that works by showing an alternative solution:

void MyCompositeTask()
{
  var result = First();
  Second(result);
}
Task.Factory.StartNew(() => MyCompositeTask());

这看起来更直观:我们将MyCompositeTask传递给TPL来运行. TPL不在乎我们在回调中做什么.我们可以做任何我们想做的事情,包括调用多个方法并传递结果.

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.

这篇关于Continuation Task在与先前相同的线程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆