2013-07-13 115 views
17

我想了解如何在使用異步/等待模式時從事件更新UI。 以下是我在WinForm應用程序上使用的測試代碼。我甚至不確定這是否正確。有什麼必要允許pwe_StatusUpdate方法更新UI?在那裏引發了跨線程操作錯誤。使用asyc等待事件更新UI

感謝您的閱讀。

// calling code 
    ProcessWithEvents pwe = new ProcessWithEvents(); 
    pwe.StatusUpdate += pwe_StatusUpdate; 
    await pwe.Run(); 



void pwe_StatusUpdate(string updateMsg) 
    { 
     // Error Here: Cross-thread operation not valid: Control '_listBox_Output' accessed from a thread other than the thread it was created on. 
     _listBox_Output.Items.Add(updateMsg); 
    } 

-

// Class with long running process and event  
public delegate void StatusUpdateHandler(string updateMsg); 

public class ProcessWithEvents 
    { 
    public event StatusUpdateHandler StatusUpdate; 

    public async Task Run() 
    { 
     await Task.Run(() => 
     { 
      for (int i = 0; i < 10; i++) 
       { 

        RaiseUpdateEvent(String.Format("Update {0}", i)); 

        Thread.Sleep(500); 
       } 
      }); 

     } 

     private void RaiseUpdateEvent(string msg) 
     { 
     if (StatusUpdate != null) 
      StatusUpdate(msg); 
     } 
    } 

-

回答

20

The async pattern has support for progress updates

簡而言之,您的async方法可能需要IProgress<T>,並且您的調用代碼在該接口的實現中通過(通常爲Progress<T>)。

public class ProcessWithUpdates 
{ 
    public async Task Run(IProgress<string> progress) 
    { 
    await Task.Run(() => 
    { 
     for (int i = 0; i < 10; i++) 
     { 
     if (progress != null) 
      progress.Report(String.Format("Update {0}", i)); 
     Thread.Sleep(500); 
     } 
    }); 
    } 
} 

// calling code 
ProcessWithUpdates pwp = new ProcessWithUpdates(); 
await pwp.Run(new Progress<string>(pwp_StatusUpdate)); 
+0

「//調用代碼」部分中的ProcessWithProgress應該是「ProcessWithUpdates」嗎? –

+0

@Brock:是的。編輯。 –

2

,您應該使用的ControlInvoke方法。它在Control的線程中執行一些代碼。您也可以檢查InvokeRequired屬性以檢查是否需要調用Invoke方法(它檢查調用方是否與創建控件的線程不同)。

簡單的例子:

void SomeAsyncMethod() 
{ 
    // Do some work    

    if (this.InvokeRequired) 
    { 
     this.Invoke((MethodInvoker)(() => 
      { 
       DoUpdateUI(); 

      } 
     )); 
    } 
    else 
    { 
     DoUpdateUI(); 
    } 
} 

void DoUpdateUI() 
{ 
    // Your UI update code here 
} 

在某些情況下,你應該在調用Invoke方法之前檢查的ControlIsHandleCreated財產。如果IsHandleCreated返回false,那麼你需要等待控件的句柄將創建

+0

這個偉大的工程,以及進度suggession。我非常感謝這兩種方法。 – ChiliYago

+0

使用異步模式時,您不應該自己實現此功能。 'Progress '已經在它創建的SynchronizationContext上執行。 – cremor

+0

簡單的解決方案。很棒。 –

2

//只是聲明瞭一個代表,像這樣

delegate void Add(string msg); 

//然後聲明委託方法像這樣:

var add = new Add((msg) => { 
    _listBox_Output.Items.Add(msg); 
}); 

//現在只需撥打代表:

void pwe_StatusUpdate(string updateMsg) 
    { 

     _listBox_Output.Invoke(add,updateMsg); 
    } 
0

下面是另一個例子

async void DoExport() 
{ 
    var rMsg = ""; 
    var t = await Task<bool>.Factory.StartNew(() => ExportAsMonthReport(LastMonth.Name, LastYear.Name, out rMsg)); 

    if (t) 
    { 
      BeginInvoke((Action)(() => 
      { 
       spinnerMain.Visible = false; 
       menuItemMonth.Enabled = true; 

       MetroMessageBox.Show(this, rMsg, "Export", MessageBoxButtons.OK, MessageBoxIcon.Information, 200); 
      })); 
    } 
    else 
    { 
      BeginInvoke((Action)(() => 
      { 
       spinnerMain.Visible = false; 
       menuItemMonth.Enabled = true; 

       MetroMessageBox.Show(this, rMsg, "Export", MessageBoxButtons.OK, MessageBoxIcon.Error, 200); 
      })); 
    } 
}