A simple example of C # Thread in asp.net

Source: Internet
Author: User

The Thread class can create and control threads. The constructor overload of the Thread class is a principal parameter that accepts the ThreadStart and ParameterizedThreadStart types. Next we will use an example to explain how to use the Thread class to create a simple Thread.

The code is as follows: Copy code


Static void Main (string [] args)
        {
# Example of no parameters for region Thread
Thread th = new Thread (ThreadChild );
Th. Start ();
Console. WriteLine ("Main Thread Start! ");
# Endregion
        }
Static void ThreadChild ()
        {
Console. WriteLine ("Child Thread Start! ");
        }

 

The output of the program running results cannot be guaranteed first. Because the thread is scheduled by the operating system, the thread at which the program is running can be different

 

Transmit data to the thread

The example above demonstrates how to use the Thread class to create a Thread without passing parameters. Next we will create a Thread with passing parameters. There are two ways to pass parameters to a Thread: one is to use the Thread constructor with the ParameterizedThreadStart delegate parameter, and the other is to define a custom class. First, we use the ParameterizedThreadStart delegate to create a class for passing parameters. When ParameterizedThreadStart is used, the thread entry (the method called by the thread) must have an Object-type parameter. The first thing we think of when using an Object is that the type is insecure. In addition, most binning operations are performed during Thread Execution. Let's use this method to create a thread with input parameters !!

There is no more nonsense, but the code is not directly available. Read the code !!

The code is as follows: Copy code


Static void Main (string [] args)
        {    
# Region uses parameterizedThreadStart to run a delegate with parameters
Thread th1 = new Thread (Thread_param );
Th2.Start (20 );
# Endregion
        }
Static void Thread_param (object msg)
        {
Int message = (int) msg;
Console. WriteLine ("Result: {0}", message );
        }

 

The thread created above is of an insecure type. What method is used to execute a thread with input parameters? The answer is to create a custom class, define a field in the class as an input parameter and define the main method of the thread as an instance method of the class. However, using this method, you can use generics to solve the unsafe type of ParameterizedThreadStart.

Look !!!!

The code is as follows: Copy code


Class Program
    {
Static void Main (string [] args)
        {
# Region uses a custom class to implement a thread with parameters
MyThread <string> mythread = new MyThread <string> ("Thread_child ");
Thread th3 = new Thread (mythread. ThreadChild );
Th3.Start ();
# Endregion
        }
    }
Class MyThread <T>
    {
Private T data;
Public MyThread (T data)
        {
This. data = data;
        }
Public void ThreadChild ()
        {
Console. WriteLine ("Child Thread Start! Result: {0} ", data );
        }
}

 

 

Background thread

The Thread class creates foreground threads by default, so all the threads we created earlier are foreground threads. As long as there is a front-end thread running, the application process is running. If multiple front-end threads are running and the Main () method (Main thread) ends, the application process is still activated until all front-end threads complete their tasks.

What about background threads? Obviously, it is opposite to the foreground thread. After the main thread ends, the application process is terminated. After all foreground threads end, the background threads are terminated.

During encoding, we can set the IsBackground attribute of the Thread class to determine whether the Thread is a foreground Thread or a background Thread. When IsBackground is set to False, it is the foreground thread and the background thread when IsBackground is set to true. The following example shows the difference between the foreground thread and the background thread. First, create a foreground thread.

The code is as follows: Copy code


Static void Main (string [] args)
        {
Thread th_pre = new Thread (Thread_pre)
{Name = "Thread_pre", IsBackground = flase };;
Th_pre.Start ();
Console. WriteLine ("The main thread is finished! ");
        }
Static void Thread_pre ()
        {
Console. WriteLine ("subthread starts execution! ");
Thread. Sleep (3000 );
Console. WriteLine ("sub-thread execution completed! ");
        }

From the preceding running results, we can see that after the main thread is executed, the subthread is executed successfully before the application is terminated.

Let's take a look at the background thread and the code !!

The code is as follows: Copy code


Static void Main (string [] args)
        {
Thread th_back = new Thread (Thread_back)
{Name = "Thread_back", IsBackground = true };
Th_back.Start ();
Console. WriteLine ("The main thread is finished! ");
        }
Static void Thread_back ()
        {
Console. WriteLine ("subthread starts execution! ");
Thread. Sleep (3000 );
Console. WriteLine ("sub-thread execution completed! ");
        }

 

From the running results, we can see that after the main thread ends, the process is terminated and the background thread is terminated. Therefore, there is no output information for the background thread to end.

Control thread

After we use Thread to create a Thread, we need to control the Thread.

1. Use the Start () method to make the thread in the Running state and Start execution.

2. Use the Join () method to make the thread in the WaitSleepJoin state. When the standard COM and SendMessage message pump processing continues, the call thread is blocked, until a thread is terminated or timed.

3. Using the Sleep () method also puts the thread in the WaitSleepJoin state. After the time period defined by the Sleep () method, the thread will be awakened again. ,

4. Using the Abort () method will put the thread in the ResetAbort () state. When the thread receives this command, it will throw a ThradAbordException type exception.

Look at the code

The code is as follows: Copy code


Using System;
Using System. Text;
Using System. Threading;
Namespace ConsoleThreadContral
{
Class Program
    {
Static void Main (string [] args)
        {
Console. WriteLine ("mainThread Start! ");
Thread th = new Thread (newThread );
Th. Start (); // change the status of the current instance to ThreadState. Running.
Console. WriteLine ("newThread State: {0}", th. ThreadState );
Th. Join (100); // during the process of continuing to execute standard COM and SendMessage message pump, the call thread is blocked until a thread ends or passes through a specified time.
Console. WriteLine ("newThread State: {0}", th. ThreadState );
Th. Abort (); // ThreadAbortException is triggered on the thread that calls this method to start the process of terminating this thread. Calling this method usually terminates the thread.
Console. WriteLine ("newThread State: {0}", th. ThreadState );
        }
Static void newThread ()
        {
Console. WriteLine ("newThread Start! ");
Thread. Sleep (10000 );
Console. WriteLine ("newThread Complete! ");
        }
    }
}

Example

This document uses a simple example to illustrate how to create a thread and a thread with parameters. It should be noted that the parameters of the ThreadStart and ParameterizedThreadStart functions are a function name and implemented through delegation, the former creates a thread without parameters, and the latter creates a thread with parameters.

The code is as follows: Copy code

Using System;
Using System. Collections;
Using System. Text;
Using System. Threading;
    
Namespace thread {
Class thread {
Public static void print1 (){
For (int I = 1; I <20; I ++ ){
Console. WriteLine ("Thread name: {0}, number = {1}", Thread. CurrentThread. Name, I );
Thread. Sleep (200 );
    }
    }
Public static void print2 (){
For (int I = 220; I <245; I ++ ){
Console. WriteLine ("Thread name: {0}, number = {1}", Thread. CurrentThread. Name, I );
Thread. Sleep (200 );
    }
    }
Public static void print3 (){
For (int I = 530; I <552; I ++ ){
Console. WriteLine ("Thread name: {0}, number = {1}", Thread. CurrentThread. Name, I );
Thread. Sleep (200 );
    }
    }
Public static void print (object obj ){
// Int star = (para) obj). getA (), end = (para) obj). getB ();
Int star = (int) (ArrayList) obj) [0]), end = (int) (ArrayList) obj) [1]);
For (int I = star; I <end; I ++ ){
Console. WriteLine ("Thread name: {0}, number = {1}", Thread. CurrentThread. Name, I );
Thread. Sleep (200 );
    }
    }
Class para {
Private int;
Private int B;
    
Public void add (int a, int B ){
This. a =;
This. B = B;
    }
Public int getA (){
Return this.;
    }
Public int getB (){
Return this. B;
    }
    }
Static void Main (string [] args ){
Console. WriteLine ("Main thread start .");
/******
Thread t1 = new Thread (new ThreadStart (print1 ));
T1.Name = "thread1 ";
Thread t2 = new Thread (new ThreadStart (print2 ));
T2.Name = "thread2 ";
Thread t3 = new Thread (new ThreadStart (print3 ));
T3.Name = "thread3"; t1.Start ();
T2.Start (); t3.Start ();
T1.Join ();
T2.Join ();
T3.Join ();
*******/
Thread t = new Thread (new ParameterizedThreadStart (thread. print ));
// Para p = new para ();
// P. add (1, 20 );
ArrayList list = new ArrayList ();
List. Add (1 );
List. Add (20 );
T. Name = "thread1 ";
T. Start (list );
Thread tt = new Thread (new ParameterizedThreadStart (thread. print ));
// Para p = new para ();
// P. add (1, 20 );
List [0] = 220;
List [1] = 245;
Tt. Name = "thread2 ";
Tt. Start (list );
Thread ttt = new Thread (new ParameterizedThreadStart (thread. print ));
// Para p = new para ();
// P. add (1, 20 );
List [0] = 530;
List [1] = 552;
Ttt. Name = "thread3 ";
Ttt. Start (list );
T. Join ();
Console. WriteLine ("Main thread finish .");
Console. ReadLine ();
    }
    }
    }

C # Thread class: determines whether multiple threads have ended.

The thread can also use the counter method, that is, set a thread counter for all threads to be monitored. Each time a thread starts, add 1 to the counter in the thread execution method, if a thread ends (minus 1 for this counter at the end of the thread execution method), minus 1 for this counter. Then start a thread and monitor the counter at a certain interval. If the Brown counter is 0, all threads are finished. Of course, this monitoring thread can also be used to monitor the counter at the end of each working thread (after the code for the counter minus 1). That is to say, each worker thread is also responsible for detecting this counter before exiting. When using this method, do not forget to synchronize the counter variable. Otherwise, unexpected consequences will occur.

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.