C # Multithreading Simple example explanation

Source: Internet
Author: User
Tags thread class

Reprint URL: http://www.knowsky.com/540518.html

. NET defines the function of multithreading in the System.Threading namespace. Therefore, to use multiple threads, you must first declare a reference to this namespace (using System.Threading;).
A. Start a thread
As the name suggests, "Start a thread" is to create a new and start a thread meaning, the following code can be implemented:
Thread thread1 = new Thread (new ThreadStart (Count));
The Count is the function that will be executed by the new thread.
B. Killing threads
"Kill a Thread" is to destroy the first thread, in order not to waste effort, before killing one of the threads, it is best to determine whether it is still alive (through the IsAlive property), and then can call the Abort method to kill the thread.
C. Pausing a thread
It means to keep a running thread dormant for a period of time. such as thread. Sleep (1000); is to keep the thread dormant for 1 seconds.
D. Priority
There's no need to explain this. The hread PR iority attribute in the thread class is used to set the priority, but it does not guarantee that the operating system will accept the priority. The priority of a thread can be divided into 5 kinds: Normal, AboveNormal, BelowNormal, highest, Lowest. The specific implementation examples are as follows:
Thread. Priority = Threadpriority.highest;
E. Suspending Threads
The suspend method of the thread class is used to suspend the thread until the resume is invoked before the thread can continue execution. If the thread is already suspended, it will not work.
if (thread. ThreadState = threadstate.running)
{
Thread. Suspend ();
}
F. Recovery threads
Used to recover a thread that has been suspended so that it continues to execute, and it will not work if the thread is not suspended.
if (thread. ThreadState = threadstate.suspended)
{
Thread. Resume ();
}


An example is listed below to illustrate the simple threading functionality. This example comes from the Help document.
Using System;
Using System.Threading;

Simple threading Scenario:start A static method running
On a second thread.
public class Threadexample {
The ThreadProc method was called when the thread starts.
It Loops ten times, writing to the console and yielding
The rest of its time slice each time, and then ends.
public static void ThreadProc () {
for (int i = 0; i < i++) {
Console.WriteLine ("ThreadProc: {0}", i);
Yield the rest of the time slice.
Thread.Sleep (0);
}
}

public static void Main () {
Console.WriteLine ("Main Thread:start a second thread.");
The constructor for the Thread class requires a ThreadStart
Delegate that represents the "method" to is executed on the
Thread. C # simplifies the creation of this delegate.
Thread t = new Thread (new ThreadStart (ThreadProc));
Start ThreadProc. On a UN IP rocessor, the thread does not get
Any processor time until the main thread yields. Uncomment
The thread.sleep that follows T.start () to the difference.
T.start ();
Thread.Sleep (0);

for (int i = 0; i < 4; i++) {
Console.WriteLine ("Main thread:do some work.");
Thread.Sleep (0);
}

Console.WriteLine ("Main Thread:call Join (), to wait until ThreadProc ends.");
T.join ();
Console.WriteLine ("Main Thread:ThreadProc.Join has returned. Press Enter to end program. ");
Console.ReadLine ();
}
}

The output generated by this code is similar to the following:
Main Thread:start a second thread.
Main Thread:do some work.
threadproc:0
Main Thread:do some work.
Threadproc:1
Main Thread:do some work.
Threadproc:2
Main Thread:do some work.
Threadproc:3
Main Thread:call Join (), to the wait until ThreadProc ends.
Threadproc:4
Threadproc:5
Threadproc:6
Threadproc:7
Threadproc:8
Threadproc:9
Main Thread:ThreadProc.Join has returned. Press Enter to end program.


In Visul C # system.threading namespaces provide classes and interfaces that allow multithreaded programming, in which threads are created in the following three ways: Thread, ThreadPool, Timer. Here is a brief description of how they are used.

First, Thread
This is perhaps the most complex method, but it provides a variety of flexible controls over threads. First you have to use its constructor to create a thread instance with simple arguments, only one ThreadStart delegate: Public Thread (ThreadStart start), and then call Start () to start it, Of course you can use its Priority property to set or get its run priority (enum Threadpriority:normal, Lowest, Highest, BelowNormal, AboveNormal).
The following example first generates two thread instances T1 and T2, then set their priority, then start the two threads (two threads are basically the same, but they output is not the same, T1 is "1", T2 is "2", according to their respective number of output characters can be roughly see their CPU time ratio, This also reflects their respective priorities).
static void Main (string[] args)
{
thread T1 = new Thread (new ThreadStart (THREAD1));
Thread t2 = new Thread (new ThreadStart (Thread2));

T1. Priority = Threadpriority.belownormal;
T2. Priority = Threadpriority.lowest;
T1. Start ();
T2. Start ();
}
public static void Thread1 ()
{
for (int i = 1; i < 1000; i++)
{//write a "1" on each loop
Dosth ();
Console.Write ("1");
}
}
public static void Thread2 ()
{
for (int i = 0; i < 1000; i++)
{//write a "2" on each loop
Dosth ();
Console.Write ("2");
}
}
public static void Dosth ()
{//used to simulate complex operations
for (int j = 0; J < 10000000; J + +)
{
int a=15;
A = A*a*a*a;
}
}
The results of the above programs are:
11111111111111111111111111111111111111111121111111111111111111111111111111111111111112
11111111111111111111111111111111111111111121111111111111111111111111111111111111111112
11111111111111111111111111111111111111111121111111111111111111111111111111111111111112

From the above results, we can see that the T1 thread takes up more CPU time than T2, because the T1 priority is higher than the T2, if we set the T1 and T2 priority to normal, the result is shown in the following figure:
121211221212121212121212121212121212121212121212121212121212121212121
212121212121212121212121212121212121212121212121212121212121212121212
121212121212121212
As we can see from the example above, it is constructed like a Win32 worker thread, but it is much simpler to simply take the function that the thread is calling as a delegate, and then construct the thread instance with the delegate as a parameter. When start () is invoked, the corresponding function is called, starting with the first line of the function.
Next we combine the thread's ThreadState properties to understand the threading control. ThreadState is an enumeration type that reflects the state of the thread.  When a thread instance is just created, its threadstate is unstarted, and its threadstate is Running after it is invoked to start (); After this thread has started, if you want it to pause (block), you can call the Thread.Sleep () method, which has two overloaded methods (sleep (int), Timespan), but only a different format for the amount of time, when this function is called within a thread. It means that this thread will block for some time (the time is determined by the number of milliseconds passed to sleep, or timespan, but if the argument is 0 to suspend this thread so that other threads can execute, specifying Infinite to block the thread indefinitely), At this point its threadstate will become waitsleepjoin, and it is worth noting that the sleep () function is defined to be static. This also means that it cannot be combined with a thread instance, nor does it exist similar to T1. Call to Sleep (10). As such, the sleep () function can only be invoked by the thread that needs "sleep" and not by other threads, just as it is a personal matter that cannot be decided by someone else. But when a thread is in a waitsleepjoin state and has to wake it up, you can use the Thread.Interrupt method, which throws the threadinterruptedexception on the thread, and let's take a look at an example ( Notice how sleep is invoked):
static void Main (string[] args)
{
thread T1 = new Thread (new ThreadStart (THREAD1));
T1. Start ();
T1. Interrupt ();
E.waitone ();
T1. Interrupt ();
T1. Join ();
Console.WriteLine ("T1 is End");
}
static AutoResetEvent E = new AutoResetEvent (false);
public static void Thread1 ()
{
Try
{//From the parameters can be seen will cause hibernation
Thread.Sleep (Timeout.infinite);
}
catch (System.Threading.ThreadInterruptedException e)
{//Interrupt Handler
Console.WriteLine ("1st Interrupt");
}
E.set ();
Try
{//Hibernate
Thread.Sleep (Timeout.infinite);
}
catch (System.Threading.ThreadInterruptedException e)
{
Console.WriteLine ("2nd Interrupt");
}//suspend for 10 seconds.
Thread.Sleep (10000);
}
The results of the operation are: 1st interrupt
2nd Interrupt
(10s) T1 is end


From the example above we can see that the Thread.Interrupt method can wake a program from a blocking (waitsleepjoin) state into the corresponding interrupt handler, and then continue to execute (its threadstate also becomes running), The following points must be noted in the use of this function:
1, this method not only can wake up by sleep caused by blocking, and all can lead to line Cheng

Related Article

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.