2013-03-28 22 views
0

我在我的应用程序中使用任务类。这不是WPF应用程序!现在的问题是有没有从任务体在UI线程调用函数中的任何可能性,就像这样:C#.NET 4 Can Task可以在UI线程上提供通知吗?

var task = new Task(() => DoSmth(1)); 
task.Start(); 

public void DoSmth(int arg) 
    { 
     //smth 
     CallNotifFuncOnUIThread(() => Notify(1)); 
     //smth ELSE 
     CallNotifFuncOnUIThread(() => Notify(2));//notify AGAIN 
     //smth ELSE 
    } 

public void Notify(int arg) 
    { 
     progressBar1.Value = arg; 
    } 

或者,也许有这个问题的其他解决办法?我知道BackgroundWorker类,但Tasks如何?

+0

相关:http://stackoverflow.com/questions/5971686 – dtb

+1

它是WPF?如果是这样,请使用['Dispatcher'](http://msdn.microsoft.com/pl-pl/library/system.windows.threading.dispatcher.aspx),即'Application.Current.Dispatcher',它将给予你的UI调度员。当然,如果你想在后台处理过程中的某个地方更新UI,如果你只是想在最后更新它,在延续中使用适当的调度器上下文。 –

+0

这里是类似的问题的答案:http://stackoverflow.com/questions/15327717/algorithm-progress-callback/15661639#15661639使用TPL INotify接口 – semeai

回答

1

您可以随时调用其他方法您DoSth()内

Dispatcher.Invoke(...); 
Dispatcher.BeginInvoke(...); 

您也可以用户Task.ContinueWith(...)到任务完成处理后,做某事......

1

如果你有一个任务,你可以

Task.Factory.StartNew(() => DoSomethingOnGUI(), TaskScheduler.FromCurrentSynchronizationContext()); 
0

与Windows窗体和progressBar1组件ityou可以使用TPL:通过提供正确的调度程序启动它的GUI线程上210接口为Task

private void Form1_Load(object sender, EventArgs e) 
    { 
     Progress<int> progress = new Progress<int>(); 
     var task = Alg(progress); 
     progress.ProgressChanged += (s, i) => { UpdateProgress(i); }; 
     task.Start(); 
    } 

    public void Notify(int arg) 
    { 
     progressBar1.Value = arg; 
    } 

    public static Task Alg(IProgress<int> progress) 
    { 
     Task t = new Task 
     (
      () => 
      { 
       for (int i = 0; i < 100; i++) 
       { 
        Thread.Sleep(100); 
        ((IProgress<int>)progress).Report(i); 
       } 
      } 
     ); 
     return t; 
    } 
相关问题