Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Cross Thread

0.00/5 (No votes)
23 Oct 2006 1  
We can't perform operations on a control, if that control was created by another thread. When we try to do thatm, we will get cross thread exceptions.

Sample Image - Cross_Thread.jpg

Introduction

We can't perform operation on a control, if that control was created by another thread. While doing this kind of operations, we get Cross Thread is not valid. like that.

About this code

In this sample, i have used only one text box. I am planning to display GUID in textbox with uncondition loop. If we do that without thread, the application will be hang. so, I have created a thread in form load event.
private void Form1_Load(object sender, EventArgs e)
{
       guidThread = new Thread(new ThreadStart(CreateNewGuid));
       guidThread.Start();
}

Thread Method

There is a method CreateNewGuid() to generate guid with unconditional loop. Here, invoking a delegate event GuidThreadCallBack() to assgin the new generated guid to text box.
 public delegate void GuidThreadCallBack();
while (true)
  {
    newGUID = Guid.NewGuid().ToString();
    try
    {
     this.Invoke(new GuidThreadCallBack(setTextBoxValue));
    }
    catch { guidThread.Abort(); }
  }

Delegate Event Method

This method will assign the value to the text box. While assging the value to textbox, the delegate event method will use which thread created the text box.
private void setTextBoxValue()
 {
   textBox1.Text = newGUID;
   textBox1.Refresh();
 }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here