I need to operate multiple threads recently, but there is a problem in C #. If the control in the main thread is operated in the thread, an error is prompted or the operation has a problem. To do this, you can use the delegate proxy method, the following is an example prepared by myself based on the content on the Internet: (the program code is included after the explanation)
For the software control interface, you can add column information in columns in the listview control. To achieve the preceding effect, you need to set the view attribute in the listview control to details.
To use multithreading, you must reference system. threading.
In addition, to transmit data information between different methods, you can set global variables:
Public thread = NULL;
Public int ino = 0;
Public String strno = NULL;
The landlord found that if the project contains multiple interfaces, the best way to pass data between interfaces is to add a class and apply for a variable in the class. In this project, add a class ccvalue, and define variables in ccvalue
Public static bool thstop = false; // apply for the bool variable control line to start and stop
Code of the Enable button:
Private void button#click (Object sender, eventargs E)
{
Thread = new thread (New threadstart (dowork ));
Thread. Start ();
}
Exit button Code: (this button only exits the thread, not the exit window)
Private void button3_click (Object sender, eventargs E)
{
Ccvalue. thstop = true;
Thread. Join (1 );
}
Hello button Code: (this button is mainly used to test whether multithreading is implemented)
Private void button2_click (Object sender, eventargs E)
{
MessageBox. Show ("hello ");
}
Multi-threaded operation code:
Public Delegate void myinvoke (string str1, string str2 );
Public void dowork ()
{
While (! Ccvalue. thstop)
{
If (ccvalue. thstop)
{
Break;
}
Else
{
Strno = ino. tostring (). Trim ();
Myinvoke MI = new myinvoke (updateform );
This. begininvoke (MI, new object [] {"I Am a text box", strno}); // note that the new object [] {"I Am a text box", strno} and
// Updateform (string param1, string param2) corresponds to the variable,
// That is, the method updateform (string param1, string
Param2)
// Transmit data
Thread. Sleep (1000 );
Ino ++;
}
}
}
Public void updateform (string param1, string param2)
{
This. textbox1.text = param1 + param2;
Listviewitem item = new listviewitem (param1 );
Item. subitems. Add (param2 );
Listview1.items. Add (item );
}
After the preceding operations are completed, multiple threads will be implemented.