C # Multithreaded Programming instance threads interact with forms
Code:
Public partial class Form1:form {//Declare thread array thread[] workthreads = new THREAD[10]; Public Form1 () {InitializeComponent (); }//This delegate allows an asynchronous call to add Item delegate void Additemcallback (string text) to the listbox; This method demonstrates how thread-safe mode is lowered with a control on a Windows Form. private void AddItem (string text) {if (this.listBox1.InvokeRequired) {Addite Mcallback d = new Additemcallback (AddItem); This. Invoke (d, new object[] {text}); } else {this.listBox1.Items.Add (text); }}//Data acquisition method public void Dataget () {while (true) {Addit EM ("OK"); Thread.Sleep (1000); }//If this method exits, then the thread exits}///<summary>///boot thread//</summary> <param name= "Sender" ></param>//<param Name= "E" ></param> private void Button1_Click (object sender, EventArgs e) {//loop Create and start thread Line 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 not running, start if (Workthreads[i]. ThreadState = = Threadstate.aborted | | Workthreads[i]. ThreadState = = threadstate.stopped) {Workthreads[i] = new Thread (New Threadstar T (Dataget)); Workthreads[i]. Name = i.ToString (); Workthreads[i]. Start (); }else{Workthreads[i]. Start (); } } }}///<summary>//Stop thread///</summary>//<param name= "Sender" ></param>//<param name= "E" ></param> private void button2_click (object sender, Eventa RGS e) {//Loop stop thread execution for (int i = 0; i < workthreads.length; i++) { If the thread exists and the state is not stopped or terminated, then the thread is terminated if (workthreads[i]! = null && workthreads[i]. ThreadState! = threadstate.stopped && workthreads[i]. ThreadState! = threadstate.aborted) {workthreads[i]. Abort (); } } }