Wednesday, September 9, 2015

C# Equivalent of DoEvents

I have been looking for a long time for an equivalent to Visual Basic's DoEvents statement.

DoEvents allows your code to yield execution to other threads in order to share processing time.  This could be do in a loop to allow you to process an iteration of the loop and when done yield.  This is often done to attempt to keep the UI responsive.  After each iteration you would call DoEvents thus allowing the UI some processing time.

I was studying today about multi threading and asynchronous processing when I came across some code that did a loop and called Thread.Sleep(0) at the end of each iteration.  Supposedly this yields execution without causing the loop to execute longer, since the sleep is for zero milliseconds.  Since the thread goes to sleep, other threads can then take over and release control when it is done.

I think you can use DoEvents in C# by using the the Visual Basic library, but from what I have seen people saying that is not recommended.  This is why I have been looking for a native C# method of doing this.

Visual Basic
        For Each file In files
            DoFileStuff()
            Application.DoEvents()
        Next

This is useful if DoFileStuff() updates the UI. DoEvents() would then let go of control, so the UI could take a turn and refresh itself.

C#
        foreach (var file in files)
        {
            DoFileStuff();
            Thread.Sleep(0);
}
The thread goes to sleep and immediately wakes up ready to be scheduled for execution when it is its turn again.

No comments: