One of the most cumbersome things you will ever have to do with Winforms is updating your User interface while receiving events from another thread. For example, you have a long-running method, but you want to show a progress bar while it runs. To make the application responsive during execution of this method, you decide to run the method in a new Thread. No problems! However, you can't just call methods on the progress bar control from the running method. The reason lies in the fact that the Progress bar is part of the Form thread, which is different from the Method thread. Calling methods on another thread can lead to application hangs and other great stuff.
The only way to call methods on the progress bar control is by calling the Form.Invoke()
method, which takes a delegate to a method which would perform this operation. Form.Invoke()
performs the invocations using the Form's thread, which is the "good" way to perform these operations.
This means that every time you want to update your UI from another thread, you'd need to create 2 separate methods and 2 separate delegates. One method and delegate to recieve the event from the thread which then " Invoke
"s another delegate to a method on the form, whcih actually updates the UI. Agh . Isn't that wonderful?
Comments