我想了解如何在使用異步/等待模式時從事件更新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);
}
}
-
「//調用代碼」部分中的ProcessWithProgress應該是「ProcessWithUpdates」嗎? –
@Brock:是的。編輯。 –