Google
 

Monday, May 28, 2007

The Meaning of Control.CheckForIllegalCrossThreadCalls

From MSDN:
Gets or sets a value indicating whether to catch calls on the wrong thread that access a control's Handle property.

Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in system.windows.forms.dll)


When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property. Set CheckForIllegalCrossThreadCalls to true to find and diagnose this thread activity more easily.

Here is some testing code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TryControl.CheckForIllegalCrossThreadCalls
{
public partial class Form1 : Form
{
System.Timers.Timer timer
= new System.Timers.Timer();
public Form1()
{
InitializeComponent();
timer.Elapsed
+= new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled
= true;
//Control.CheckForIllegalCrossThreadCalls = true;
}

void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{

this.richTextBoxTimer.Text = e.SignalTime.ToLongTimeString();
}

}
}

Because the richtextbox is not thread safety, when you run with debugger you will get an exception:
"Cross-thread operation not valid: Control 'richTextBoxTimer' accessed from a thread other than the thread it was created on."

However, if you run without debugger, the application will run ok.
See:

When I set the Control.CheckForIllegalCrossThreadCalls as "true" and run the it without debugger, the appliation will show as:

Conclusion:
1.When you run with debugger, the incorrect cross thread calling exception will be thrown. To set the Control.CheckForIllegalCrossThreadCalls as true the exception message will be more understandable.

2.When
set Control.CheckForIllegalCrossThreadCalls as true and run without debugger, the incorrect calling will be skipped.

REF:http://blogs.msdn.com/jfoscoding/archive/2005/05/12/416910.aspx

No comments: