Step by Step C #2. Thread control)

Source: Internet
Author: User

Overview

Multithreading is an important aspect of attention when building large systems, especially in efficiency (how fast does the system run ?) And performance (the system works normally ?) To make a trade-off between them. The proper use of Multithreading can greatly improve the system performance.

What is a thread?
Every program running on the system is a process. Each process contains one or more threads. The process may also be a dynamic execution of the entire program or some programs. A thread is a set of commands or special segments of a program. It can be executed independently in the program. It can also be understood as the context of code execution. Therefore, a thread is basically a Lightweight Process, which is responsible for executing multiple tasks in a single program. Generally, the operating system is responsible for scheduling and execution of multiple threads.

 

Common models in Win32 environments.

· Single-threaded Model

In this thread model, only one thread can exist in a process, and the remaining processes must wait until the current thread finishes running. The disadvantage of this model is that it takes a long time for the system to complete a small task.

· Block thread model (single-threaded Multi-block model STA)

In this model, a program may contain multiple execution threads. Here, each thread is divided into a separate block in the process. Each process can contain multiple blocks and share data in multiple blocks. The Program specifies the thread execution time in each block. All requests are serialized through the Windows message queue, which ensures that only one block can be accessed at a time. Therefore, only one single process can be executed at a specific time point. This model is better than the single-threaded model in that it can respond to the tasks of multiple user requests at the same time, not just individual user requests. But its performance is not very good, because it uses a serialized thread model, the task is executed one by one. (This model is equivalent to executing another thread in multiple threads until the execution of the thread ends and then starting another thread)

· Multi-threaded block model (free thread Block Model)

The multi-threaded block model (MTA) has only one block in each process, rather than multiple blocks. This single block Controls Multiple Threads rather than a single thread. Message Queue is not required because all threads are part of the same block and can be shared. Such programs are faster than single-threaded models and Stas, because they reduce the system load and can be optimized to reduce the system idle time. These applications are generally complex because programmers must provide thread synchronization to ensure that threads do not concurrently request the same resource, thus causing competition. It is necessary to provide a lock mechanism. However, this may cause a system deadlock.

 

How does multithreading work in. NET?

In essence and structure,. NET is a multi-threaded environment. There are two main multithreading methods. NET advocate: Use ThreadStart to start your own processes directly (use ThreadPool. queueUserWorkItem) or indirect (such as Stream. beginRead or BeginInvoke) use the ThreadPool class. In general, you can "manually" Create a New thread for long-running tasks. In addition, for Short-running tasks, especially those that often need to be started, the process pool is a good choice. The process pool can run multiple tasks at the same time and use framework classes. When resources are in short supply and need to be synchronized, it can restrict only one thread to access resources at a certain time point. This situation can be considered as implementing a lock mechanism for the thread. The base class of the thread is System. Threading. All threads are managed through CLI.

 

How to Use threads

Using System. Threading;
All classes related to multithreading applications are stored in the System. Threading namespace.

The Thread class is used to create a Thread.

ThreadPool is used to manage thread pools.

If you want to use multithreading in your application, you must include this Thread class.


The Thread class has several crucial methods:

Start (): Start the thread.
Sleep (int): a static method that pauses the specified number of milliseconds of the current thread.
Abort (): This method is usually used to terminate a thread.
Suspend (): This method does not terminate the unfinished thread. It only suspends the thread and can be recovered later.

Resume (): Resume the execution of threads suspended by the Suspend () method.

 

Simple thread example

Class Program
{
Static void Main (string [] args)
{
ThreadStart threadStart = new ThreadStart (SayHello );
Thread thread = new Thread (threadStart );
Thread. Start ();
Thread. Sleep (5000 );
}

Public static void SayHello ()
{
Console. Write ("Spring Yang say hello to you. hello, every one .");
}
}

 

Running result:

 

Passing a single parameter

Class Program
{
Static void Main (string [] args)
{
String message = "Hello everyone .";
ParameterizedThreadStart threadStart = new ParameterizedThreadStart (SayHello );
Thread thread = new Thread (threadStart );
Thread. Start (message );
Thread. Sleep (5000 );
}

Public static void SayHello (object message)
{
Console. Write ("Spring Yang say hello to you. {0}.", message );
}
}

 

Result:

 

 

Multiple parameters are passed:

Class Program
{
Static void Main (string [] args)
{
ThreadTest threadTest = new ThreadTest ("spring yang", "How are you? ");
ThreadStart threadStart = new ThreadStart (threadTest. SayHello );
Thread thread = new Thread (threadStart );
Thread. Start ();
Thread. Sleep (5000 );
}


}

Public class ThreadTest
{
Private string _ userName;
Private string _ message;

Public string UserName
{
Get {return _ userName ;}
Set {_ userName = value ;}
}

Public string Message
{
Get {return _ message ;}
Set {_ message = value ;}<

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.