When we do the WinForm application, most of the time we encounter the problem of using the control information on the multithreading interface. However, we do not use the traditional method to do this problem, I will explain in detail below.
First look at the traditional approach:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(ThreadFuntion);
thread.IsBackground = true;
thread.Start();
}
private void ThreadFuntion()
{
while (true)
{
this.textBox1.Text = DateTime.Now.ToString();
Thread.Sleep(1000);
}
}
}
Running this code, we will see that the system throws an exception: Cross-thread operation not Valid:control ' textBox1 ' accessed from a thread other than the thread it W As created on. This is because. NET 2.0 has since tightened security and does not allow the control's properties to be accessed directly across threads in WinForm. So how to solve this problem, there are several scenarios.
In the first scenario, we add a code to the Form1_Load () method:
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
Thread thread = new Thread(ThreadFuntion);
thread.IsBackground = true;
thread.Start();
}
After adding this code, you will find that the program is working correctly. This code means that in this class we do not check whether the invocation of a cross thread is legitimate (if there is no exception to this sentence, then the system and the default method of not checking). However, this method is not advisable. When we look at the definition of checkforillegalcrossthreadcalls this property, we find that it is static, which means that no matter where we modify the value in the project, he will be working globally. And there are exceptions like this across thread access, which we usually check. If the other person in the project modifies this attribute, then our scenario fails and we have to take another approach.