C # multi-threaded programming instance thread and form Interaction
C # multi-threaded programming instance thread and form Interaction
Code:
Public partial class Form1: Form {// declare the Thread array Thread [] workThreads = new Thread [10]; public Form1 () {InitializeComponent ();} // This delegate allows asynchronous calls to add Item delegate void AddItemCallback (string text) to Listbox; // This method demonstrates how to call controls on Windows Forms in thread-safe mode. Private void AddItem (string text) {if (this. listBox1.InvokeRequired) {AddItemCallback d = new AddItemCallback (AddItem); this. invoke (d, new object [] {text});} else {this. listBox1.Items. add (text) ;}// data collection method public void shortet () {while (true) {AddItem (OK); Thread. sleep (1000);} // if this method exits, the thread exits }////// Start the thread /////////Private void button#click (object sender, EventArgs e) {// create a loop and start the thread to execute for (int I = 0; I <workThreads. length; I ++) {if (workThreads [I] = null) {// if the thread does not exist, create workThreads [I] = new Thread (new ThreadStart (DataGet); workThreads [I]. name = I. toString (); workThreads [I]. start ();} else {// already exists. if it is not running, Start if (workThreads [I]. threadState = ThreadState. aborted | workThreads [I]. threadState = ThreadState. stopped) {workThreads [I] = new Thread (new ThreadStart (DataGet); workThreads [I]. name = I. toString (); workThreads [I]. start ();} else {workThreads [I]. start ();}}}}////// Stop the thread /////////Private void button2_Click (object sender, EventArgs e) {// loop stop thread execution for (int I = 0; I <workThreads. length; I ++) {// if the thread exists and the status is neither stopped nor terminated, terminate the thread if (workThreads [I]! = Null & workThreads [I]. ThreadState! = ThreadState. Stopped & workThreads [I]. ThreadState! = ThreadState. Aborted) {workThreads [I]. Abort ();}}}}