The front section came into contact with multi-thread, except for MSDN and 9CBS, it also looked at the following information, more nice entry information:
"
C # multi-thread application discussion
http://www.soft6.com/know/detail.asp?id=baajgj
In June 2000, Microsoft released a new programming language - C #. C # is a modern, object-oriented language that enables developers to quickly establish extensive applications on the Microsoft .NET framework. C # supports the application of the free-threaded, and multiple threads can access the same set of shared data.
Example Program Description The instance program of this article includes a list box, three buttons. The program uses a new thread to run a background processing, and the result is displayed in the list box. Button Button1 Start a calculation square thread. Button button stops the background processing thread. Button Button3 exits the program. The program operation is shown in Figure 1.
Use thread first to create a background task running on the new thread. The code shown in Table 1 performs a relatively long running process - an infinite loop.
Table 1, the background processing private void backgroundprocess () {INT i = 1; while (true) {// add a project listbox1.Items.Add ("Items:" i.toString ()); i ; Thread.sleep (2000); // Specify the time}} of the thread sleep}} This code is infinite loop, and a project is added in the list box each time.
After the processing code is specified, this code needs to be assigned to a thread and start it. For this purpose, you need to use a thread object, which is part of the system.threaming namespace in the .NET schema class. When instanting a new thread class, it is necessary to transmit one reference block of the code block executed in the thread class constructor to the instance. The code shown in Table 2 creates a new thread object and transmits a reference to the BackgroundProcess to the object.
Table 2, using Thread T1, T2; // illustrates the Form class member T1 = New Thread (new threadstart ()); t1.start (); // The two lines are placed in the form of the form
ThreadStart represents the method performed on the thread, here is a delegate object to the BackgroundProcess method. In C #, a delegate is a type of security, object-oriented function pointer. After instantification of the thread, you can start executing the code by calling the start () method of the thread.
The control thread can control the state of the thread by calling the thread object after the thread starts. You can suspend the execution of a thread by calling the Thread.Sleep method, which can receive a integer value to determine the time of thread sleep. For the instance programs of this article, in order to increase the speed of the list item slower, an SLEEP method is placed in it.
The thread enters the sleep state by calling thread.sleep (system.threading.timeout.infinite), but this calling time is uncertain. To interrupt this sleep, you can call the Thread.Interrupt method.
You can suspend the thread by calling the thread.suspend method. Suspend can be suspended until another thread calls Thread.Resume. The difference between sleep and hang is that the hang does not immediately let the thread enter a waiting state, and the thread will not hang until .NET Runtime thinks it is already a safe place to hang it, and sleep will Let the thread enter a state of waiting. Table 3, the execution of the thread private void button2_click (Object Sender, System.EventArgs E) {t1.abort ();
The thread.abort method can stop the execution of a thread. The instance program of this article stops the background processing by adding a button Button2, calling the Thread.abort method in the event handler, as shown in Table 3.
This is the power of multi-threads. The user interface responds quickly because the user interface runs in a separate thread, and the background's processing runs in another thread. When the user presses the button Button2, it will be immediately responded immediately, and the background processing is stopped. Many complex features of multi-threaded multi-threading are required to transmit data through multi-threaded program. One of the questions is how to incorporate the data of the program from the constructor of the thread class. For the process of putting it in another thread, neither the parameter is given to it, or it cannot be returned by it because the process of incoming a thread constructor cannot have any parameters or return values. In order to solve this problem, you can package the process into a class, so that the parameters of the method can use the fields in the class.
This article gives a simple example and calculates a number of squares. In order to use this process in a new thread, it encapsulate it into a class, as shown in Table 4.
Start the Calcsquare process on a new thread using the code shown in Table 5.
Table 4, calculate a number of square table 5, start Calcsquare process PUBLIC CLCSQUARE process PUBLIC DOUBLIC DOUBLE SQUARE; public void Double () {square = value * value;}} private void button1_click Object sender, system.eventargs e) {squareclass osquare = new squareclass (); t2 = new three (osquare.calcsquare); osquare.Value = 30; t2.start ();}
In the above example, the thread is started, and there is no inspection of the Square value in the class, because even if the START method of the thread is called, it cannot be ensured that the method is performed immediately. There are several ways to get the required values from another thread, one of which triggers an event when the thread is completed. The code shown in Table 6 joined the event declaration for SquareClass.
Table 6, was added to SquareClass event declaration public delegate void EventHandler (double sq); // delegate type described public class SquareClass {public double Value; public double Square; public event EventHandler ThreadComplete; // described event object public void CalcSquare () { Square = Value * Value; // specified event handler ThreadComplete = new EventHandler (SquareEventHandler); if (! ThreadComplete = null) ThreadComplete (Square); // trigger event} public static void SquareEventHandler (double Square) // define event handlers Program {MessageBox.show (Square.toString ());}} For this approach, it is important to note that the event handler SquareEventHandler runs in thread T2 that generates the event instead of running in the thread executed. Synchronous threads provide several ways to synchronize the synchronization of threads. In the above example of the above-described calculation, it is necessary to synchronize with the thread that performs the calculated, so that it is waiting to perform and result. Another example is that if an array is sorted in other threads, wait for the processing to be completed before using the array. In order to achieve synchronization, C # provides a Lock declaration and thread.join method.
Lock declaration
Table 7, use LOCK Declaration Public Void Calcsquare1 () {Lock (TypeOf (SquareClass)) {Square = Value * Value;}}
LOCK can get a unique lock of an object reference, as long as it is transmitted to the Lock when used. With this unique lock, you can ensure that multiple threads do not access shared data or code executed on multiple threads. To get a lock, you can use the System.Type object associated with each class. The System.Type object can be obtained by using the TypeOf operation, as shown in Table 7.
Thread.join method
Table 8 using methods Thread.Join private void button1_Click (object sender, System.EventArgs e) {SquareClass oSquare = new SquareClass (); t2 = new Thread (new ThreadStart (oSquare.CalcSquare)); oSquare.Value = 30; t2 .Start (); if (t2.join (500)) {MessageBox.show (OSQUARE.SQUARE.TOSTRING ());}}
The thread.join method can wait for a specific time until a thread is completed. If the thread is completed within the specified time, thread.join will return True, otherwise it returns false. In the above square example, if you do not want to use the trigger event, you can call Thread.join method to determine if the calculation is completed. The code is shown in Table 8.
Conclusion This article describes the use and control methods of C # in C # through an example program to explore how to transmit data and threads through multi-threaded program. According to the analysis herein, it is very simple to use the thread in C #. C # supports the application of the self-contained thread, improves the utilization of resources, and the response speed of the program has also improved. Of course, data transfer and thread synchronization are also brought. --------------------------------------- http://www.microsoft.com/china /msdn/archives/library/dnnetcomp/html/netcfmultithreadedApp.asp#netcfmultithreadAPPP_topic2 Update User Interface from Auxiliary Thread
You can update the user interface (UI) from other threads other than the UI thread using Control.invoke. This method performs a proxy in the control thread context on the UI thread. The .NET Framework Lite only supports the overloaded Control.Invoke method in the .NET Framework full version. Control.invoke only uses a parameter: a proxy that specifies which method to perform on the UI thread. The type of agent must be EventHandler and have the following signature:
Void MyFunctionName (Object Sender, Eventargs E)
It should be noted that if you want to update your UI in the secondary thread, you must call Application.doEvents (). Call Application.doEvents () ensures that any event excited by the auxiliary thread is processed by the UI thread.
The following sample code shows how to create a secondary thread, then update the listbox control called ListBox1 from the UI thread and the secondary thread:
// This variable will keep some text set by the auxiliary thread
Public String Message = ""
// Create a secondary thread, then add the project from the UI thread to
// ListBox
Public void dothreading ()
{
// Create and start auxiliary thread
ThreadStart Starter = New ThreadStart (this.Updatelistbox);
Thread T = New Thread (Starter);
T.Start ();
// Circulation 4 times, add a message to listbox each time
For (int i = 0; i <4; i );
{
This.ListBox1.Items.Add ("message from the UI thread");
THISTBOX1.UPDATE ();
// Treat queue in the UI thread
Application.doevents ();
// hang the process for a second
Thread.sleep (1000);
}
THISTBOX1.ITEMS.Add ("Previous message from the UI thread");
THISTBOX1.UPDATE ();
}
Public void updatelistbox ()
{
For (int J = 0; j <5; j ) {
/ / Settings To add from the auxiliary thread to listbox
// message
THIS.MESSAGE = "The number of cycles of the auxiliary thread =" j.totring ();
/ / Call workerupdate in the thread context of ListBox
// method
This.ListBox1.invoke (New EventHandler (WorkerUpdate);
Thread.sleep (700);
}
}
/ / For updating listbox from the auxiliary thread
// call the agent
Public void Workerupdate (Object Sender, Eventargs E)
{
this.listbox1.items.add (this.Message);
THISTBOX1.UPDATE ();
}
To use this code, do the following:
Create a new smart device application using the Windows Application Template. Add a ListBox control into a Windows Form (the default name is ListBox1). The statement will be added to the top of the Form1.cs file using System.ThReading; Paste the code into the FORM1 class. Call the dothreading method from the Form1 constructor.
========= - ============================================================================================================================================================================================= =================== Multithreaded system article: http://blog.9cbs.net/paul_ni/ Author translated 5 pieces of articles, although there are too many words, but It is still very inspiring after it. Http://blog.9cbs.net/younther/ A more popular Delegate and multi-threaded article http://dev.9cbs.net/develop/Article/53/53246.SHTM for Invoke and BeginInvoke and more Thorough understandings of thread programming http://dev.9cbs.net/develop/article/18/18280.SHTM This article is in the use of multiple autosetEvent event classes, with the cancel button, I also used a similar method in the next project, solved a big problem, ^ _ ^ http: //dev.9cbs.net/develop/Article/28/28254.shtm