C # multithreaded programming instance threads interacting with windows
Code:
Public partial class Form1:form {//Declare thread array thread[] workthreads = new THREAD[10]; Public Form1 () {InitializeComponent (); }//This trust consents to an asynchronous call to add Item delegate void Additemcallback (string text) to the listbox; Such a method demonstrates how thread-safe mode is lowered with a control on a Windows window. 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 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 run for (int i = 0; i < workthreads.length; i++) {if (workthreads[i] = = null) {//Assuming the thread does not exist, create Workthreads[i] = new Thread (new ThreadStart (Dataget)); Workthreads[i]. Name = i.ToString (); Workthreads[i]. Start (); } else {//already exists, assuming it is 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_cli CK (object sender, EventArgs e) {//Loop stop thread run for (int i =0; i < workthreads.length; i++) {//Assume that the thread exists and that the state is not stopped or terminated, then terminate the thread if (workthreads[i]! = NULL && Workt Hreads[i]. ThreadState! = threadstate.stopped && workthreads[i]. ThreadState! = threadstate.aborted) {workthreads[i]. Abort (); } } } }
Source code Download: http://download.csdn.net/detail/testcs_dn/7618881
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
C # multithreaded programming instance threads interacting with windows