Problem
Because in the beginning of C # when the use of thread delegation to execute functions, is to not let the software forms suspended animation. So use the code below:
Thread th = new Thread (getform); Creating Threads
Th. Start ();
Need to be introduced before use: using System.Threading;
However, in the GetForm function, I called the command that modifies the contents of the form control.
Textbox.text= "false";
A direct error.
Invalid inter-thread operation: access it from a thread that does not create a control "textbox"
All right. Find information, see how to fix it,
Workaround:
1, directly ignore the thread permission check.
Public Form1 ()
{
InitializeComponent ();
Control.checkforillegalcrossthreadcalls = false;
}
We have added this code: Control.checkforillegalcrossthreadcalls = false; Ignore Thread permission checks
Personal understanding: Such direct neglect may have other problems, so we are not recommended, but also indeed at certain times can be used, after all, convenient ...
2. Use delegates for security changes, using delegate and invoke to control control information from other threads (Network replication instructions)
Direct copy of code on the network is viewed more clearly in C #
It still seems relatively simple, just this will make the window unresponsive, because in the Infinite Refresh window, however. Will there be a better way to deal with it.
The Final Solution:
private void Button1_Click (object sender, EventArgs e) { var th = new Thread (() = { //label1. Enabled = false; Label1. Crossthreadcalls (() = {Label1. Enabled =!label1. Enabled; }); Writemessage (DateTime.Now.ToString ()); }); Th. IsBackground = true; Th. Start (); } public void Writemessage (String msg) { Label1. Crossthreadcalls (() = { Label1. Text = msg; });
Before using, we create a new class.
Using system.threading;using system.windows.forms;namespace windowsformsapplication1{public static class Class1 {//<summary>/// cross-threaded access control executes a delegate on a control///</summary>// <param name= "ctl" > control </param> //<param name= "del" > Executed delegate </param> public static void Crossthreadcalls (this Control ctl, ThreadStart del) { if (Del = = null) return; if (CTL. invokerequired) ctl. Invoke (del, null); else del ();}} }
In the end, we came up with this workaround. It's good.
I just record in the process of learning, welcome to discuss
Original address: http://www.lazyw.org/weituo.html
C # The workaround for the thread access control can call this method directly