2011-10-03 25 views

回答

5

您可以传入一个委托来调用定期结果和一个SynchronizationContext任务可以用来在正确的线程上调用回调。这基本上是BackgroundWorker这样做的方式(以及C#5的异步功能将“知道”回拨的位置) - 它在调用线程上捕获SynchronizationContext.Current,然后调用Post(IIRC)将消息发布到正确的背景。然后,您只需要将原始回调包装到SendOrPostCallback中,该回调在到达正确的线程时执行。

编辑:样例程序:

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); 
      } 
     }); 
    } 
} 
+0

可以为用户提供代码的例子吗? – RBZ

+0

@Kaizen:完成。请注意'StartTask'方法如何知道它是Windows窗体应用程序的事实 - 相同的代码可以在WPF应用程序中工作。 –

+0

杰出!谢谢! – RBZ

0

根据您使用的应用程序,可能会有不同的方法。

  • 的WinForms:Control.Invoke
  • WPF/Silverlight中/ WP7及其衍生物:Dispatcher.Invoke
  • 一些其他类型的应用程序:定义什么UI线程意味着第一?
相关问题