Friday, March 17, 2006

Controls and Threading

Controls are not thread safe! you should never try to access a control or modify it from a different thread than the one the control exists on. If you do strange results will happen.

Fortunately controls have two methods that help us overcome this issue with ease.
control.invoke() to do simple tasks and control.beginInvoke() for longer running tasks that we want to have happen on a background thread.

Here is a simple example of using beginInvoke()

dim params() as object = {me, System.EventArgs.Empty}
control.BeginInvoke(new System.EventHandler(Addressof UpdateUi), params)

private sub UpdateUi(sender as object, e as eventArgs)
lblStatus.text = "Finished"

as you can see we pass in an array of parameters. In this case the sender and eventargs.
You could also use custom event args to accomplish this:

MyProgressEvent e = new MyProgressEvent(msg, percentDone);
object[] pList = { this, e };

private void UpdateUI(object sender, MyProgressEvents e) {
lblStatus.Text = e.Msg;
myProgressControl.Value = e.PercentDone;

Sometimes in our code we will not know if we are on another thread or not. Thankfully again there is a method that lets us know that as well. It is control.InvokeRequired.
It will return false if the calling thread is the thread the control exists on. It will return true when the caller is on another thread.


Post a Comment

<< Home