Tôi đang cố gắng hiểu cách cập nhật giao diện người dùng từ một sự kiện trong khi sử dụng mẫu không đồng bộ/chờ. Dưới đây là mã thử nghiệm tôi đang sử dụng trên một ứng dụng WinForm. Tôi thậm chí không chắc chắn đây là cách đúng đắn để đi về nó. Điều gì là cần thiết để cho phép phương thức pwe_StatusUpdate cập nhật giao diện người dùng? Lỗi hoạt động chéo được ném ở đó.Cập nhật giao diện người dùng từ các sự kiện bằng cách sử dụng asyc await
Cảm ơn bạn đã đọc.
// 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' trong phần' // calling code' có phải là 'ProcessWithUpdates' thay thế không? –
@Brock: Yup. Đã chỉnh sửa. –