Chi*_*ago 20 c# asynchronous async-await
我试图了解如何在使用async/await模式时从事件更新UI.下面是我在WinForm应用程序上使用的测试代码.我甚至不确定这是正确的方法.允许pwe_StatusUpdate方法更新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);
}
Run Code Online (Sandbox Code Playgroud)
-
// 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);
}
}
Run Code Online (Sandbox Code Playgroud)
-
Ste*_*ary 26
简而言之,您的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));
Run Code Online (Sandbox Code Playgroud)
小智 7
你应该使用Invoke的方法Control。它在 Control 的线程中执行一些代码。您还可以检查InvokeRequired属性以检查是否需要调用Invoke方法(它检查调用者是否位于与创建控件的线程不同的线程上)。
简单的例子:
void SomeAsyncMethod()
{
// Do some work
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)(() =>
{
DoUpdateUI();
}
));
}
else
{
DoUpdateUI();
}
}
void DoUpdateUI()
{
// Your UI update code here
}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,您应该在调用方法之前检查IsHandleCreated属性。如果返回 false 那么你需要等待 Control 的句柄将被创建ControlInvokeIsHandleCreated