2013-07-13 119 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); 
      })); 
    } 
}