C # Multi-threaded application technology face-to-face discussion

Source: Internet
Author: User
Tags constructor execution join reference sleep thread thread class tostring
Multithreading Instance Program Description
The example program in 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 starts a thread that calculates the square. Button Button2 stops the background processing thread. Button Button3 exit the program. The program runs as shown in Figure 1.
  
Using threads
First, create a background task that runs on a new thread. The code shown in table 1 executes a fairly long running process----an infinite loop.
  
Table 1, background handler
private void Backgroundprocess ()
{
int i= 1;
while (true)
{
Add an item to the list box
ListBox1.Items.Add ("iterations:" + i.tostring ());
i + +;
Thread.Sleep (2000); Specify when a thread sleeps
}
}
  
This code loops endlessly, adding an item to the list box each time it is executed.
  
After you specify the processing code for a job, you need to assign the code to a thread and start it. To do this, you need to use thread object, which is. NET Schema class as part of the System.Threading namespace. When instantiating a new thread class, you need to pass a reference to the code block that executes in the thread class constructor to the instance. The code shown in table 2 creates a new thread object and passes a reference to the backgroundprocess to the object.
  
Table 2, usage of threads
Thread t1,t2; Description for Form class members
T1 = new Thread (new ThreadStart (backgroundprocess));
T1. Start (); The above 2 lines are placed in the form's Load event
  
ThreadStart represents a method executed on a thread, which is a delegated object to the Backgroundprocess method. In C #, a delegate is a type-safe, object-oriented function pointer. After the thread is instantiated, you can start executing code by calling the thread's start () method.
  
   Control Threads
After a thread has started, you can control the state of the thread by calling the method of the Thread object. You can pause the execution of a thread by calling the Thread.Sleep method, which can receive an integer value to determine when the thread sleeps. For the instance program in this article, a call to the sleep method is placed in order to slow the increase in the list item.
  
You can get a thread into hibernation by calling Thread.Sleep (System.Threading.Timeout.Infinite), but the dormant time of the call is indeterminate. To break this hibernation, you can call the Thread.Interrupt method.
  
You can suspend a thread by calling the Thread.Suspend method. Suspend can suspend one thread until another thread calls Thread.Resume. The difference between hibernation and hanging is that the hang does not immediately allow the thread to enter a waiting state, and the thread does not hang until. NET runtime that it is now a safe place to suspend it, while hibernation will immediately let the thread into a waiting state.
  
Table 3, stopping the execution of threads
private void button2_click
(object sender, System.EventArgs e)
{T1.   Abort (); }
  
The Thread.Abort method can stop the execution of one thread. The instance program in this article stops background processing by adding a button button2 and calls the Thread.Abort method in the event handler, as shown in table 3.
  
This is the strong point of multithreading. The user interface responds very quickly because the user interface runs in a separate thread, and the processing in the background runs on another thread. When the user presses the button button2, it immediately gets a response and stops the background processing.
  
   transferring data through multithreaded programs
In practice, you need to use many of the complex features of multithreading. One of the problems is how to pass data from a program to or from the constructor of a thread class. For a procedure placed in another thread, you cannot pass parameters to it or return a value because the procedure passed into the thread builder cannot have any arguments or return values. To solve this problem, you can encapsulate the procedure in a class so that the parameters of the method can use the fields in the class.
  
In this paper, a simple example is given to calculate the square of a number. To use this procedure in a new thread, encapsulate it in 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 the Square table 5 of a number, 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 Button1_Click (object sender, System.EventArgs e)
{
Squareclass osquare =new squareclass ();
t2 = new Thread (new ThreadStart (Osquare.calcsquare));
Osquare.value = 30;
T2. Start ();
}
  
In the example above, when the thread starts, the square value in the class is not checked, because even if the thread's Start method is invoked, the method is not guaranteed to execute immediately. There are several ways to get the desired value from another thread, one of which is to trigger an event when the thread finishes. The code shown in table 6 adds an event declaration to Squareclass.
  
Table 6, adding event declarations for Squareclass
public delegate void EventHandler (double sq); Description Delegation Type
public class Squareclass
{
public double Value;
public double Square;
public event EventHandler Threadcomplete; Description Event Object
public void Calcsquare ()
{
Square = value * value;
Specifying an event handler
Threadcomplete+=new EventHandler (Squareeventhandler);
if (threadcomplete!=null) threadcomplete (Square); Triggering events
}
public static void Squareeventhandler (double Square)//Defining an event handler
{MessageBox.Show (square.tostring ()); }
}
  
For this approach, note that the event handler Squareeventhandler runs in the T2 of the thread that generated the event, rather than in the thread on which the form executes.
  
   Synchronizing Threads
C # provides several methods for synchronizing threads. In the example of calculating the squares above, you need to synchronize with the thread that performs the calculation so that it is finished and the results are obtained. Another example is that if you sort an array in another thread, you must wait for the processing to complete before using the array. To achieve synchronization, C # provides a lock declaration and Thread.Join method.
  
Lock declaration
  
Table 7, using the lock declaration
public void CalcSquare1 ()
{
Lock (typeof (Squareclass))
{
Square = value * value;
}
}
  
Lock can get a unique lock that is referenced by an object, as long as the object is passed to lock when it is used. With this unique lock, you can ensure that multiple threads do not access shared data or code that executes 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 the Thread.Join method
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 completes. If the thread completes within a specified time, Thread.Join returns True, otherwise it returns false. In the above squared example, if you do not want to use the method that triggers the event, you can call the Thread.Join method to determine whether the calculation is complete. The code is shown in table 8.
  
   Conclusions
This paper illustrates the use and control method of C # thread through an example program, and probes into how to transfer data and thread synchronization problem through multithreading program. Based on the analysis of this article, it is easy to use threads in C #. C # supports the creation of free threading applications, increases resource utilization, and improves the response speed of programs. Of course, there are issues such as data transfer 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.