Avoiding “Cross-thread operation not valid” Exception With Multithreaded Applications

Unfortunately, enabling thread synchronization for controls is a very hard problem to solve–and even the most elegant solutions have considerable drawbacks. I have tried to develop a demo application in C# that avoids this exception.

public partial class Form1 : Form
{
Thread demothread, demothread1;
public delegate void SetTextCallback(string s);
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
this.demothread = new Thread(new ThreadStart(this.writetext));
this.demothread.Start();

}

private void Form1_Load(object sender, EventArgs e)
{
label1.Text = “main thread”;
}
public void writetext()
{
//Thread.Sleep(1000);
string text = “another thread”;

if (this.label1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text + ” (invoke)” });
}
else
{
this.label1.Text = “no invoke”;
}
}
public void readtext()
{
//Thread.Sleep(1000);
string text = “another thread”;

if (this.label1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(GetText);
this.Invoke(d, new object[] { text + ” (invoke)” });
}
else
{
this.label1.Text = “no invoke”;
}
}
private void SetText(string text)
{
this.label1.Text = text;
}
private void GetText(string text)
{
MessageBox.Show(this.label1.Text);
}

private void button2_Click(object sender, EventArgs e)
{
this.demothread1 = new Thread(new ThreadStart(this.readtext));
this.demothread1.Start();
}
}

Mayur Gondaliya - CTO - CaseTronyx, Inc. Director - ExaSpring Information Services Pvt. Ltd. Web Investor. Software Engineer. Workaholic. Insomniac.

Leave a Reply