Using the Begin Invoke method to update the values in other thread

Hi,

Many a times when we are working with multi threaded situation, we want to update the value of another thread from the same. Let say you are working on a windows application which creates a new thread to process some work. Now you want to update the status of work in a label in a windows application.

If you try and update the label’s text property from another thread then you will get a runtime exception. As the other thread cannot access this class variable.

To work around this we have to use the BeginInvoke method to queue the message to the proper thread. Here is the code on how to update a label in a multi threaded environment.

    private delegate void SetLabel1Textdel(string someText);

    private void UpdateLabel1Text(string someText)

    {

        // Check if an Invoke is required or Not

        if (this.InvokeRequired)

        {

            this.BeginInvoke(new SetLabel1Textdel(UpdateLabel1Text), new object[] { someText });

            return;

        }

        label1.Text = number.ToString();

Now all we need to do is to call the UpdateLabel1Text method. The method checks if the call has been made from the same thread or not. If not then it invokes the UpdateLabel1Text method of the other thread which then updates the text of the Label.

Vikram

Share this post   Email it

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2010 Vikram Lakhotia