Application.DoEvents method in winform, can't understand it, any one can explain it?
This deadlock, in its general
form – UI waiting for something that is waiting for UI – has existed ever since we started making
UI applications; it predates async-await, it predates .net and C#, it even predates asynchronous
IO in the Windows operating system. And so, unsurprisingly, there is a standard solution for this
problem already built into WinForms (and WPF and all other UI frameworks I know about). This
solution is to let the UI handle events (or “pump messages” in Windows API terminology) while
we are waiting for the background task to complete. In WinForms, we do this by calling the
Application.DoEvents method.
private void button1_Click(object sender, EventArgs ea)
{
var task = DoSomething();
while(!task.IsCompleted)#A
Application.DoEvents();#A
label1.Text = task.Result;
}
private async Task<string> DoSomething()
{
await Task.Delay(500)
return "done";
form – UI waiting for something that is waiting for UI – has existed ever since we started making
UI applications; it predates async-await, it predates .net and C#, it even predates asynchronous
IO in the Windows operating system. And so, unsurprisingly, there is a standard solution for this
problem already built into WinForms (and WPF and all other UI frameworks I know about). This
solution is to let the UI handle events (or “pump messages” in Windows API terminology) while
we are waiting for the background task to complete. In WinForms, we do this by calling the
Application.DoEvents method.
private void button1_Click(object sender, EventArgs ea)
{
var task = DoSomething();
while(!task.IsCompleted)#A
Application.DoEvents();#A
label1.Text = task.Result;
}
private async Task<string> DoSomething()
{
await Task.Delay(500)
return "done";