Cross-thread operation not valid

| August 13, 2010 | 0 Comments

What is Cross-thread operation not valid? It is a part of details of InvalidOperationException that is raised when you try to access control of one thread from another thread.

Code Snippet

There are two controls on Form Button named btnStartThread & second one is TextBox named txtName. And if you execute following code you will get exception as: Cross-thread operation not valid: Control ‘txtName’ accessed from a thread other than the thread it was created on.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;</pre>
namespace CrossX
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnStartThread_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(CallMe));
thread.Start();
}

public void CallMe()
{
this.txtName.Text = "I am from other thread";
}
}
}

But if you add following line of code in constructor you would get rid of that exception in your program. And your program works fine.

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

This property catch calls on wrong thread that access a control’s >System.Windows.Forms.Control.Handle property when an application is being debugged.

Category: .NET, Error and Solution, Tips

Leave a Reply

%d bloggers like this: