如何才能TPL任务发送中间结果到父线程? [英] How can a TPL task send intermediate results to the parent thread?
问题描述
我正在与第三方物流,需要有一个长期运行的TPL任务将结果发送到父UI线程不终止。我曾尝试多种方法,并已在Google上搜寻了不少。有谁知道如何做到这一点与TPL?
I am working with TPL and need to have a long running TPL task send results to the parent UI thread without terminating. I have tried several approaches and have been googling quite a bit. Does anyone know how to make this happen with TPL?
推荐答案
您可以传递一个委托具有周期性结果打电话,和<一href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx"><$c$c>SynchronizationContext$c$c>该任务可以用它来调用在正确的线程回调。这基本上是的BackgroundWorker
做它的方式(和方式的C#5异步功能将知道里打电话) - 它捕捉<一href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.current.aspx"><$c$c>SynchronizationContext.Current$c$c>调用线程上,然后调用<一个href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.post.aspx"><$c$c>Post$c$c> (IIRC)发布消息到正确的上下文中。然后,您只需要包装在一个<一个原始的回调href="http://msdn.microsoft.com/en-us/library/system.threading.sendorpostcallback.aspx"><$c$c>SendOrPostCallback$c$c>它执行它时,它得到了正确的线程。
You could pass in a delegate to call with periodic results, and a SynchronizationContext
which the task could use to invoke the callback on the correct thread. That's basically the way that BackgroundWorker
does it (and the way that the async feature of C# 5 will "know" where to call you back) - it captures SynchronizationContext.Current
on the calling thread, then calls Post
(IIRC) to post a message to the right context. You then just need to wrap the original callback in a SendOrPostCallback
which executes it when it's got to the right thread.
编辑:示例程序:
using System;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
class Test
{
static void Main()
{
Form form = new Form();
Label label = new Label();
form.Controls.Add(label);
form.Load += delegate { HandleLoaded(label); };
Application.Run(form);
}
static void HandleLoaded(Label label)
{
Action<string> callback = text => label.Text = text;
StartTask(callback);
}
static void StartTask(Action<string> callback)
{
SendOrPostCallback postCallback = obj => callback((string) obj);
SynchronizationContext context = SynchronizationContext.Current;
Task.Factory.StartNew(() => {
for (int i = 0; i < 100; i++)
{
string text = i.ToString();
context.Post(postCallback, text);
Thread.Sleep(100);
}
});
}
}
这篇关于如何才能TPL任务发送中间结果到父线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!