Blog

MAKE CROSS THREAD METHOD CALLS USING INVOKE METHOD OF THE CONTROL

Posted by Jaish Mathews Blogs | Learn .NET Apr 22, 2010
Cross threading is a phenomina normally happening in any of application debug session. Developer may not able to understand what's this all about. He may not actually coded for any such scenario like Threading. But this exception may raise especially in side a method where you are accessing any of the GUI control menthod. One natural scenaio will happen, once you are handling with FielSystemWatcher class. But here 1st I will create a sceanrio and then will give you 2 way resolution too.

Create a Scenario for CrossThread Exception
--------------------------------------------
CrossThread means your are in a thread and trying to access any resource in side another Thread. In .net winform all controls you pasted will be rendred and finally created in a builtin assigned thread. Now you may have Therad programming in your code like you are invoking a method using a separate Thread. Inside this method, when you try to access any of your controls, you will get CrossThread exception. Below is a CrossThread exception sample .
My Form Load code to call a method named "Method1" in a seprate Thread.
-----------------------------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
          
            Thread th = new Thread(new ThreadStart(Method1));
            th.Start();
}

My "Method1" code, which is trying to access a ListBox control named, "listBox1"
private void Method1()
{
 listBox1.Items.Add("Jaish Mathews");
}
You just run this code and you will get an error which saying
"Cross-thread operation not valid: Control 'listBox1' accessed from a thread other than the thread it was created on."
This is the whole discussed CrossThread exception. 'listBox1' is created in an assigned Thread and your are running "Method1" in a different Thread and trying to access 'listBox1' in side "Method1". This is a clear ThreadCrossing scenario. Now how you can handle it. Yes, we can do it using an asynchronous way.
Method to Handle CrossThread Execution
--------------------------------------
Here basically we are using the "Invoke" method of the control to invoke a specific method inside that control rather than execute an inline direct method call. A property named "InvokeRequired" is available to determine whether we need CrossThread handling.
1. Use Custom Delegates- You will create a delegate with same prototype of the method needs to be invoked. Then we fire the delgate and through delgate our method also will be fired.Below is the code
//This should be a class level declaration
 private delegate void myDelegate();
//Below is the modified Method1
private void Method1()
{
//We need to handle CrossThred           
if (listBox1.InvokeRequired)
{
  //Through delegate firing the method "Method1"
                myDelegate md = new myDelegate(Method1);
        //Calling Invoke method to invoke the delegate and consequenty invoke Method1
               this.Invoke(md, null);
}
//No need to handle CrossThread           
else
{
                listBox1.Items.Add("Jaish Mathews");
}
           
}
2. Use Builtin MethodInvoker Delegate - Here we are skipping the delegate declration from our part and using a builtin delegate named MethodInvoke. Just look the below modified code for Method1 which is handling the CrossThread using builting delegate
//Below is the modified Method1
private void Method1()
{
//We need to handle CrossThred           
if (listBox1.InvokeRequired)
{
   this.Invoke(new MethodInvoker(Method1));
}
//No need to handle CrossThread           
else
{
                listBox1.Items.Add("oooo");
}
}
So remind these matters whenever getting an exception like
"Cross-thread operation not valid: Control 'listBox1' accessed from a thread other than the thread it was created on."
          
COMMENT USING
PREMIUM SPONSORS
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.
SPONSORED BY
  • MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.