<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dot Net Thoughts &#187; Cross thread operation</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/cross-thread-operation/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>thoughts about .Net, WPF, Sharepoint, Javascript and more.</description>
	<lastBuildDate>Wed, 28 Jul 2010 09:59:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>System.InvalidOperationException – Cross-thread operation not valid</title>
		<link>http://www.dotnetthoughts.net/2010/02/05/system_invalidoperationexception_cross_thread_operation_not_valid/</link>
		<comments>http://www.dotnetthoughts.net/2010/02/05/system_invalidoperationexception_cross_thread_operation_not_valid/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 19:54:58 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Cross thread operation]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=763</guid>
		<description><![CDATA[System.InvalidOperationException &#8211; Cross-thread operation not valid: Control &#8216;xxxxx&#8217; accessed from a thread other than the thread it was created on. Normally we get this exception when we try to modify some control property from another thread. This is because when a program executes the operating system will assign a thread for the creation of UI [...]]]></description>
			<content:encoded><![CDATA[<p><em>System.InvalidOperationException &#8211; Cross-thread operation not valid: Control &#8216;xxxxx&#8217; accessed from a thread other than the thread it was created on</em>. Normally we get this exception when we try to modify some control property from another thread. This is because when a program executes the operating system will assign a thread for the creation of UI elements and for the changes of the UI. Only this thread has got the permission to change or control UI elements created. If you creates other threads with the help of Thread class from System.Threading namespace, doesn’t have enough privileges to change or control the UI elements of the Main thread. To resolve this issue, we need write delegates and need to invoke the methods from other threads using these delegates.</p>
<p>This sample code is doing some long operation in a separate thread and try to update the UI from the new thread.</p>
<pre class="brush: csharp;">

private void Form1_Load(object sender, EventArgs e)
{
    this.threadStart = new ThreadStart(LongProcess);
    this.thread = new Thread(this.threadStart);
    this.thread.Start();
}
private void LongProcess()
{
    for (int i = 0; i &lt; 100; i++)
    {
        Thread.Sleep(100);
        //This will throw an exception like this
        //System.InvalidOperationException - Cross-thread operation not valid:
        //Control 'textBox1' accessed from a thread other than the thread it was created on.
        this.textBox1.Text = i.ToString();
    }
}
</pre>
<p>And here is the source code which will fix the issue with delegates and Control.Invoke method</p>
<pre class="brush: csharp;">
private ThreadStart threadStart;
private Thread thread;
private delegate void UpdateTextDelegate(string text);
private void Form1_Load(object sender, EventArgs e)
{
    this.threadStart = new ThreadStart(LongProcess);
    this.thread = new Thread(this.threadStart);
    this.thread.Start();
}

private void LongProcess()
{
    for (int i = 0; i &lt; 100; i++)
    {
        Thread.Sleep(100);
        //This will resolve the cross thread invalid operation exception.
        this.UpdateText(i.ToString());
    }
}

private void UpdateText(string text)
{
    //Checks whether the called required to invoke the &quot;Invoke&quot; method.
    if (this.textBox1.InvokeRequired)
    {
        UpdateTextDelegate updateTextDelegate = new UpdateTextDelegate(UpdateText);
        //Calling the invoke method of the control with the parameter.
        this.textBox1.Invoke(updateTextDelegate, new object[] { text });
    }
    else
    {
        this.textBox1.Text = text;
    }
}
</pre>
<p>Thanks to Praveen for helping me out. Happing Coding <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>EDIT</strong>: In case WPF applications, we don&#8217;t have InvokeRequired property available for Controls. Instead we need to use Dispatcher.CheckAccess() method. We can rewrite the UpdateText method like the following</p>
<pre class="brush: csharp;">
private void UpdateText(string text)
{
if (this.textbox1.Dispatcher.CheckAccess())
{
    this.textbox1.Content = text;
}
else
{
UpdateTextDelegate updateTextHandler = new UpdateTextDelegate(UpdateText);
this.textbox1.Dispatcher.Invoke(updateTextHandler, new object[] { text });
}
}
</pre>
<p>Thanks to Sivadas for his valueable comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/02/05/system_invalidoperationexception_cross_thread_operation_not_valid/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
