C # Introduction to multithreading

Source: Internet
Author: User

 Instance program description
The instance program in this article includes a list box and three buttons. The program uses a new thread to run a background processing, and the results are displayed in the list box. Click button1 to start a computing square thread. Click button2 to stop the background processing thread. Click button3 to exit the program. The program running status is 1.
  
Thread used
First, create a background task running on the new thread. The code shown in Table 1 executes a fairly long running process-an infinite loop.
  
Table 1. background processing programs
Private void backgroundprocess ()
{
Int I = 1;
While (true)
{
// Add a project to the list box
Listbox1.items. Add ("iterations:" + I. tostring ());
I ++;
Thread. Sleep (2000); // specifies the thread sleep time
}
}
  
The Code contains an infinite loop. Each execution adds a project to the list box.
  
After specifying the processing code for a job, you need to allocate the code to a thread and start it. To this end, you need to use a thread object, which is part of the system. Threading namespace in the. NET architecture class. When instantiating a new Thread class, you need to transmit a reference to the code block executed in the Thread class constructor to this instance. The code shown in Table 2 creates a new thread object and transmits a reference of backgroundprocess to this object.
  
Table 2. Use of threads
Thread T1, T2; // The description is a form class member.
T1 = new thread (New threadstart (backgroundprocess ));
T1.start (); // place the above two rows in the load event of the form
  
Threadstart indicates the method to be executed on the thread. Here is a delegate object to the backgroundprocess method. In C #, a delegate is a type-safe, Object-Oriented function pointer. After instantiating this thread, you can call the START () method of the thread to start code execution.
  
  Control thread
After the thread starts, you can call the method of the thread object to control the thread status. You can call the thread. Sleep method to pause the execution of a thread. This method can receive an integer value to determine the thread sleep time. For the instance program in this article, in order to make the list project increase slowly, a sleep method call is put in it.
  
You can call thread. Sleep (system. Threading. Timeout. Infinite) to bring the thread into sleep state. However, the sleep time of this call is uncertain. To interrupt this sleep, you can call the thread. interrupt method.
  
You can call the thread. Suspend method to suspend a thread. You can pause a thread until another thread calls thread. resume. The difference between sleep and suspension is that the suspension does not immediately bring the thread into a waiting state, and the thread does not pause. net runtime thinks that it is now a safe place to suspend it, and sleep will immediately let the thread enter a waiting state.
  
Table 3. Stop thread execution
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 in this article adds a button button2 to stop background processing and calls the thread. Abort method in the event processing program, as shown in table 3.
  
This is the power of multithreading. The User Interface responds quickly because the user interface runs in a separate thread, while the background processing runs in another thread. When the user presses the button button2, the user will immediately get a response and stop processing in the background.
  
  Transfer Data through multi-threaded programs
In practice, many complex features of multithreading are also needed. One of the problems is how to pass in or out program data from the constructor of the thread class. For a process put in another thread, neither a parameter can be passed to it nor the return value, because the process passed into the thread constructor cannot have any parameters or return values. To solve this problem, you can encapsulate the process into a class, so that the parameters of the method can use fields in the class.
  
This article provides a simple example to calculate the square of a number. To use this process in a new thread, encapsulate it into a class, as shown in table 4.
  
Use the code shown in Table 5 to start the calcsquare process on a new thread.
  
Table 4. Calculate a square table of numbers 5. Start the calcsquare process on a new thread.
Public class squareclass
{
Public double value;
Public double square;
Public void calcsquare ()
{
Square = value * value;
}
} Private void button#click (Object sender, system. eventargs E)
{
Squareclass osquare = new squareclass ();
T2 = new thread (New threadstart (osquare. calcsquare ));
Osquare. value = 30;
T2.start ();
}
  
In the preceding example, after the thread is started, the square value in the class is not checked, because even if the start method of the thread is called, the method in the class cannot be executed immediately. There are several methods to get the required value from another thread, one of which is to trigger an event when the thread is complete. The code shown in Table 6 adds the event declaration to squareclass.
  
Table 6. Add event Declaration for squareclass
Public Delegate void eventhandler (double sq); // specifies the delegate type.
Public class squareclass
{
Public double value;
Public double square;
Public event eventhandler threadcomplete; // specifies the event object.
Public void calcsquare ()
{
Square = value * value;
// Specify the event handler
Threadcomplete + = new eventhandler (squareeventhandler );
If (threadcomplete! = NULL) threadcomplete (square); // trigger the event
}
Public static void squareeventhandler (double square) // defines the event handler
{MessageBox. Show (square. tostring ());}
}
  
For this method, it should be noted that the event handler squareeventhandler runs in the thread T2 that generates the event, rather than in the Form execution thread.
  
  Synchronization thread
In terms of thread synchronization, C # provides several methods. In the above calculation square example, it needs to be synchronized with the thread that executes the calculation, so that it can wait until it completes execution and get the result. In another example, if you sort an array in other threads, you must wait for the processing to complete before using the array. To achieve synchronization, C # provides the lock statement and the thread. Join method.
  
Lock statement
  
Table 7. Use lock statement
Public void calcsquare1 ()
{
Lock (typeof (squareclass ))
{
Square = value * value;
}
}
  
Lock can obtain a unique lock referenced by an object. You only need to send the object to lock when using the lock operation. This unique lock ensures that multiple threads do not access Shared data or code executed on multiple threads. To obtain a lock, you can use the system. Type object associated with each class. The system. Type object can be obtained through the typeof operation, as shown in table 7.
  
Thread. Join Method
  
Table 8. Use the thread. Join Method
Private void button#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 completes. If the thread completes within the specified time, thread. Join returns true, otherwise it returns false. In the above square example, if you do not want to use the method to trigger the event, you can call the thread. Join method to determine whether the calculation is complete. The code is shown in table 8.

Related error handling skills:

Create a C # Window application
Put a listbox1 and a button1 on the form.
The code is written in this way.
Private void button#click (Object sender, eventargs E)
{
Thread Mt = new thread (New threadstart (mythread ));
Mt. Start ();
}
Private void mythread ()
{
While (true)
{
Listbox1.items. Add (datetime. Now. tostring ());
}
Compilation is normal
When a button is clicked, an error message is displayed:
System. invalidoperationexception not processed
Message = "the inter-thread operation is invalid: It is accessed by a thread that does not create the control" listbox1 ."
Why ??

 
When you call a Windows control that is not created in this thread in vs2005, an error is reported.
Use the invokerequired property of the control to determine whether invoke is required. If yes, use the invoke method of the control to execute a delegate.
For example:
If(this.txt box. invokerequired)
{
Invoke (New eventhandler (changetext), new object [] {sender, eventargs. Empty });
}
Void changetext (Object sender, eventargs e ){
This.txt box. Text = "2 ″;
}

 

 
For example:
Public partial class form1: Form
{
Private delegate void MYDEL ();
Public form1 ()
{
Initializecomponent ();
}
Private void button#click (Object sender, eventargs E)
{
Thread Mt = new thread (New threadstart (mythread ));
Mt. Start ();
}
Private void mythread ()
{
Int I = 0;
While (I <5)
{
If (this. listbox1.invokerequired)
{
Invoke (New MYDEL (mymethod ));
}
I ++;

}
}
Private void mymethod ()
{
Listbox1.items. Add (datetime. Now. tostring ());
}
}

 

 

  
  Conclusion
This article illustrates how to use and control threads in C # through an instance program, and discusses how to transfer data and synchronize threads through multi-threaded programs. According to the analysis in this article, the use of threads in C # is very simple. C # supports the creation of free-threaded applications, which improves resource utilization and program response speed. Of course, it also brings about problems such as data transmission and thread synchronization.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.