We may have an exception when we use threading: The thread operation is not valid: it is accessed from a thread that is not a richTextBox1 of the control creation. Because Windows Forms controls are not thread-safe, if several threads manipulate the state of a control, the control's state may be inconsistent, and a contention or deadlock state occurs. This situation has the following solutions:
1. The value of the Checkforillegalcrossthreadcalls property can be set to false at load time. In this way, the runtime environment does not verify that it is thread-safe. But this method is not recommended.
2. Implement thread safety using delegated mechanism. The second approach is a common approach that Microsoft proposes to use for cross threading, which is to implement it by using a proxy, which is to put the code you want to manipulate into an agent, and then hand the agent to the thread that created the control to execute your code.
Private delegate void Richtextboxcallback (); Establish a delegate public void server () {Richtextboxcallback callback = delegate ()//Use delegate {string IP = GetIP ();//Get IP address try {//Get T The port number of the XT file StreamReader Smreader = new StreamReader (path, System.Text.Encoding.UTF8);//set path string line; while (line = Smreader.readline ())!= null) {//string[] Arrstr = line. Split (' | '); Separator "|" port = int32.parse (line. Trim (). ToString ()); MessageBox.Show (port. ToString ()); } smreader.close (); Smreader.dispose (); IPAddress ipaddress = Ipaddress.parse (IP); Create server Socket listener = new TcpListener (ipaddress, Port); Start listening on server Port listener. Start (13); The message This.richTextBox1.AppendText ("Socket server has started, listening to IP + IP +" Port number: "+ port +"/n "); To access its error from a thread that is not creating it ... Start a new thread, execute method this. Startsocketlisten,//To perform validation of the operation with the client socket connection in a separate process Socketserviceflag = true;//service start thread thread = new Thread (new ThreadStart (this. Startsocketlisten)); Thread. Start (); this.button1.Enabled = false; This.button2.Enabled = true; catch (Exception Ex) {MessageBox.Show ("Server startup Error"). "+ Ex." message); } }; Richtextbox1.invoke (callback); }
Establish a commissioned private delegate void Richtextboxcallback ();
Then use the delegate Richtextboxcallback callback = Delegate () {};//Use a delegate to declare a variable callback of a delegate type, the code between {} and the code of the original method, The last Richtextbox1.invoke (callback) completes the delegate call to the control