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";
10 Replies
what part do you not understand?
also, did you copy that text from somewhere? the weird wrapping suggests as much
@eid
I'm read tutorial that explain using doevent to temporary free the ui thread which long task block and stuck it
I don't know when you'd use DoEvents, but definitely not the way it was shown there
in general you should prefer async/await to free up the UI thread
for long-running CPU-heavy work that isn't naturally async, you can make use of Task.Run
await Task.Run(() => DoComplicatedThingThatTakesAWhile());
using DoEvents for that is a pretty horrible hacki don't want to use it, i want to know the work of it, i'm reading a book in manning site, it's name c# conconrency(chapter 11) he talk about configureawait(false) and await, and he talk about doevents, i want to know the concept of it only, because i can't understand using it to allow ui thead to interacts with actions like click etc while the ui thread stucking with syncronize long task
it basically tells WinForms "take a moment to process the incoming and buffered mouse clicks, key presses, window moves, etc. then get back to me"
good, how he did that , in await i know how it does that, it does that by running the long task in background thread
it does that by running the long task in background threadnot true actually if you use Task.Run the work is handed off to the thread pool yes but things like async IO don't do that $nothread explains
There Is No Thread
This is an essential truth of async in its purest form: There is no thread.
ok, i will return to that, but my question now ,how the doevents does that job( it basically tells WinForms "take a moment to process the incoming and buffered mouse clicks, key presses, window moves, etc. then get back to me")
it just... does I guess?
Forms is basically constantly
DoEvents
ing when it's not running your own code