First, create a form, where the Start button, pause button, and ListBox text box
Second, when the start of the click, the data will be unlimited to add to the ListBox, in order to prevent the jammed and improve efficiency, it created a new thread to perform the start operation
namespaceThread again{//First, you define a delegate (a delegate is a class that defines the type of the method so that the method can be passed as a parameter to another method) Public Delegate voidWeituo ();//use this delegate to invoke methods with methods Public Partial classForm1:form {//define a delegate and start defining a thread; PrivateThread Therad; //defines a variable of type bool to store whether it is a start or a pause Private BOOLisok=true; //Define a constant Private Longi; PublicForm1 () {InitializeComponent (); //control.checkforillegalcrossthreadcalls = false;//do not check the security (generally do not use this sentence), if there is no need to entrust the sentence } Private voidButton1_Click (Objectsender, EventArgs e)//Start button{button1. Enabled=false; //When you click Start, the data is added to the listbox1, the point pause will be terminated, because it is a loop to add data, once the point begins to change will not stop, so this requires multi-threaded operation, the Start button has its own separate thread//the thread is instantiated first with aTherad =NewThread (NewThreadStart (Start));//Create a new thread for the Button1 button, so that if you click Button1, the new thread will run, without affecting the main path of the form.Therad. IsBackground =true;//Verify that the newly created thread is running in the backgroundTherad. Start (); } //define a start function to loop the data Public voidStart () { while(isOK)//Loop call delegate, change control property This work is given to the delegate to do { //calling a delegate function in a loopWeituo (); } } //define a delegate function Public voidWeituo () {//determine whether the newly created (button1) thread accesses listbox1 whether the Listbox1.invokerequired property of this control is true or false, and if other threads are accessing their own thread, the return value is Ture if(listbox1.invokerequired) {//because it is another thread that accesses its own threads, the return value is true, since it is accessed by other threads and must be transferred back to its own thread for security, which uses the delegateWeituo x =NewWeituo (Weituo);//The Weituo function becomes the new thread that can be called This. Invoke (x);//execute this delegate on the form that owns the Button1 control } Else{ListBox1.Items.Insert (0, i);//once the return value is false, the data is added to the ListBox1i++; } } Private voidButton2_Click (Objectsender, EventArgs e) {isOK=false; Button1. Enabled=true; } }}
Third, stop adding data when the pause button is clicked
Multithreaded operations (looping to add data to the listbox)