C# Cross-Thread Operations

Cross-Thread Operations

 

A cross-thread operation in C# is a call that accesses components from a different thread. Starting with .NET Framework 2.0, it is no longer optional to make proper cross-thread operations...

For example, if you try to call a Form function from a seperate thread, you will get an error message similar to:

Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.

Delegates

The answer is simply to use delegates to invoke methods that use cross-thread operations. Delegates are an elegant way to call methods that are from other threads.

 

Methods

 

For our example, we need two general methods: one to keep the loop running, and one to perform the single cross-thread operation. The whole point of even using seperate a Thread is have a thread specialized in updating part of the application without disturbing the rest.

The example, which you can download at the bottom of the page, will alternate the colors of a Panel to create a sort of blinker. By using a Thread, the Panel can be constantly updated without locking up the rest of the user interface.

InvokeRequired

 

The key for cross-thread calls is in the InvokeRequired property. When cross-threading will be required, the property will be true. You can then use delegates to invoke the method properly:

if (this.InvokeRequired)
{
     BlinkDelegate del = new BlinkDelegate(Blink); //delegate
     object[] parameters = { secondsInterval }; //parameters
     this.Invoke(del, parameters); //call
}
else
{
     //What you want done goes here
}

 

Notice that the C# function is simply calling itself if invoke is required.

The sample cross-thread operations C# application is a full working example of the techniques mentioned above...


 

 

 
11.12.2008

Отзывы и комментарии

 


 
Тема
Ваше имя
Почтовый адрес
Текст сообщения
Ключ защиты:
Защита от спама