Cross-Thread Operations
Many of you may have seen the cross-thread exception when dealing with Cross-Thread operations. For example, if you try to call a Form function from a separate 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.
That is, you cannot manA Cross-Thread operation in C# is a call that accesses components from a different thread. Handling corss-thread is a requirement starting with .NET Framework 2.0. We are going to discuss how to make cross-thread calls between controls.
Delegates
The answer is simply to use delegates to invoke methods that use cross-thread operations. Using delegates is an elegant way to call methods that are from other threads.
Methods
The example is quite simple. Let's create a blank winForm application. Then create a second thread called secondThread. Within the secondThread, we try to change the text of 'Form1'. The above exception message will pop up if the following stuff is not implemented.
InvokeRequired
The key for cross-thread calls is in the InvokeRequired property. When cross-threading will be required, the property will be true. This is a way to let you know wether you are in a cross-thread issue or not. You can then use delegates to invoke the method properly:
if (this.InvokeRequired)
{
DoSthDelegate aDelegate = new DoSthDelegate(DoSth); //delegate
this.Invoke(aDelegate); //call the method
}
else
{
//Your code here
}
Others
For more about delegates, refer to http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx
For more about Invoke method, refer to http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx
comments
0 Responses to "C# Cross-Thread Operations"Post a Comment