2015-04-12 108 views
-1

我試圖創建一個方法來封裝所有來自不同線程的GUI操作,但是當我使用它時,沒有任何反應,也沒有引發任何異常。
這是我的了:任務更新GUI

private Task t1; 
    private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     t1 = Task.Factory.StartNew(() => DoStuffInTask()) 
      .ContinueWith(tsk => Finished(tsk)); 
    } 

    private void DoStuffInTask() 
    { 
     //doing important stuff... 
     for (int i = 0; i < Int16.MaxValue; i++) 
     { 
      //Text is a property that raises INotifyPropertyChanged event 
      RunOnGui(() => { Text = i.ToString(); }); // not working, not throwing exception 
      Application.Current.Dispatcher.Invoke(() => Text = i.ToString()); // works fine 
     } 
    } 

    private void RunOnGui(Action action) 
    { 
     Application.Current.Dispatcher.Invoke(() => action); 
    } 

回答

3

此行

Application.Current.Dispatcher.Invoke(() => action); 

編譯過載public TResult Invoke<TResult>(Func<TResult> callback);

您的代碼執行Func<Action>剛剛返回的行動,而不是執行它。

你需要的是這個

private void RunOnGui(Action action) 
{ 
    Application.Current.Dispatcher.Invoke(action);//Note no lambda here 
}