我正在使用 TPL,需要长时间运行的 TPL 任务将结果发送到父 UI 线程而不终止。我尝试了几种方法,并且进行了很多谷歌搜索。有谁知道如何通过 TPL 实现这一点?
您可以传递一个委托来调用定期结果,以及SynchronizationContext http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx任务可以使用它来调用正确线程上的回调。基本上就是这样BackgroundWorker
这样做(以及 C# 5 的异步功能将“知道”在哪里给您回电的方式) - 它捕获SynchronizationContext.Current http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.current.aspx在调用线程上,然后调用Post http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.post.aspx(IIRC) 将消息发布到正确的上下文。然后,您只需将原始回调包装在SendOrPostCallback http://msdn.microsoft.com/en-us/library/system.threading.sendorpostcallback.aspx当它到达正确的线程时执行它。
编辑:示例程序:
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);
}
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)