How to Write multi-threaded applications in C #

Source: Internet
Author: User

In the past, when using VB to implement multiple threads, it was difficult. Although there are such methods, they are not satisfactory, but in C #, it is quite simple to Write multi-threaded applications. This article will give a brief introduction and serve as a reference!
. Net defines multithreading in the system. Threading namespace. Therefore, to use multithreading, you must first declare and reference this namespace (using system. Threading ;).
Even if you have no experience writing multi-threaded applications, you may have heard of the terms "start thread" and "Kill thread". Apart from these two terms, multithreading is also involved, such as "suspending Threads", "Priority", "suspending Threads", and "restoring Threads. One by one.
A. Start the thread
As the name implies, "starting a thread" means creating and starting a thread. The following code can be implemented:
Thread thread1 = new thread (New threadstart (count ));
The count is the function to be executed by the new thread.
B. Killing threads
"Killing a thread" is to remove a thread from the root. In order not to waste effort, it is best to determine whether it is still alive (through the isalive attribute) before killing a thread ), then you can call the abort method to kill this thread.
C. Pause the thread
It means to sleep a running thread for a period of time. For example, thread. Sleep (1000) is used to sleep the thread for 1 second.
D. Priority
There is no need to explain this. The thread class has a threadpriority attribute, which is used to set the priority, but the operating system cannot accept this priority. A thread has five priorities: Normal, abovenormal, belownormal, highest, and lowest. The specific implementation example is as follows:
Thread. Priority = threadpriority. Highest;
E. Thread Suspension
The suspend method of the thread class is used to suspend a thread. This thread can continue to execute until it knows to call resume. If the thread has been suspended, it will not work.
If (thread. threadstate = threadstate. Running)
{
Thread. Suspend ();
}
F. Restore the thread
It is used to restore a suspended thread to continue execution. It does not work if the thread is not suspended.
If (thread. threadstate = threadstate. Suspended)
{
Thread. Resume ();
}
The following is an example to illustrate the simple thread processing function. This example is from the help documentation.
Using system;
Using system. Threading;

// Simple threading scenario: Start a static method running
// On a second thread.
Public class threadexample {
// The threadproc method is 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 <10; 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 be executed on
// Thread. C # simplifies the creation of this delegate.
Thread t = new thread (New threadstart (threadproc ));
// Start threadproc. On a uniprocessor, the thread does not get
// Any processor time until the main thread yields. uncomment
// The thread. Sleep that follows T. Start () to see 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 of 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 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.

1. Each form has its own running on different threads. If you need to interact between forms, you need to interact between threads.

2. When the thread sleep, the system will exit the execution queue for a period of time. When the sleep ends, the system will interrupt the clock.
The thread is returned to the execution queue to resume the thread execution.

3. If the parent thread ends before the child thread, the Child thread is forced to end when the parent thread ends. The thread. Join () method waits for the parent thread until the child thread ends.
The consequence of the abort () method is the unrecoverable termination thread.

4. The starting thread can be called the main thread. If all foreground threads are stopped, the main thread can be terminated, and all background threads will be terminated unconditionally.
There is only one difference between the background thread and the foreground thread, that is, the background thread does not prevent program termination. Once all foreground threads of a process are terminated, CLR
The process will be completely terminated by calling the abort () method of any surviving background process.

6. Suspend, sleep (can be called-blocking, pause)
Unlike thread. Sleep, thread. Suspend does not stop the thread immediately. The thread can be suspended until it reaches the security point. If the thread is still
It cannot be suspended if it is not started or stopped. Calling thread. Resume will cause another thread to jump out of the pending state and continue the thread.
One thread cannot call sleep for another thread, but one thread can call suspend for another thread.
You can also use many other methods to block threads. For example, you can call thread. Join to make one thread wait for another thread (sub-thread) to stop. Use
Monitor. Wait enables a thread to wait for access to a synchronization object.

5. the keyword lock can define a piece of code as a critical section. A mutex can be executed by only one thread at a time, while other threads must wait.
When multiple threads share an object, the lock keyword should not be used. Here, monitor and monitor provide a solution to share resources with threads.
The monitor class can lock an object. A thread can operate on this object only when this lock is obtained.
For example:
Monitor. Enter (OBJ );
// Currently, the oqueue object can only be manipulated by the current thread.
Monitor. Exit (OBJ );

6. A process starts with at least one main thread (that is, the main execution instance), which is the main execution flow created when the system loads your program.
The message queue is related to the thread. On a thread like Win2k, one queue corresponds to only one queue.
When is a message queue generated? On a Win2k system, the thread has been created from the very beginning.
One thread can create multiple forms. Messages sent to these windows are uniformly sent to the same message queue. Fortunately, MSG. hwnd in the message structure indicates that the Message corresponds
Which window is related, the dispatchmessage () function is based on this to ensure that the message dispatching process is automated and there will be no errors!

7. Each form belongs to the thread that creates it. Directly accessing or indirectly asking the Form Method in other threads in the first line will lead to a runtime error (vs2005 ).
Solution: use the control. Invoke (delegate) method inherited from the form from control. This method executes the delegate pointing method on the thread that creates the form.
Note: In vs2003, you can directly or indirectly call the Form Method in another thread without causing runtime errors.

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.