Dark Horse programmer-Multithreading

Source: Internet
Author: User
Tags finally block

Multithreading means that the program executes several operations concurrently.

The. NET Framework class library adds multithreading capabilities to system. threading. Therefore, add the reference using system. threading

Thread class: Creates and controls a thread, sets its priority, and obtains its status.

Thread class constructor: thread thread_name =

Thread (threadstart): indicates the method to be called when the thread starts execution. This method is applicable to methods without parameters.

Thread (parameterizedthreadstart): parameterizedthreadstart delegate, which indicates the method to be called when the thread starts execution. This method is applicable to methods with parameter input.

A common no-parameter thread operation is as follows:

[CSHARP] view plaincopyprint?
01. Thread TD = new thread (xunhuan); // defines a thread. The parameter is a method and has no return value. The delegate is used.
02.
03. // foreground thread. The application exits only after all threads are executed. The foreground thread is used by default.
04. // backend thread. Exit when all foreground threads are finished, regardless of the background threads.
05. TD. isbackground = true; // set it to a background thread.
06. TD. Start (); // start the thread
Thread TD = new thread (xunhuan); // defines a thread. The parameter is a method and has no return value. The delegate is used.

// Foreground thread. The application exits only after all threads are executed. The foreground thread is used by default.
// Background thread. All foreground threads exit after execution, regardless of background threads.
TD. isbackground = true; // set it to a background thread
TD. Start (); // start the thread
A thread with parameters is as follows:

[CSHARP] view plaincopyprint?
01. Thread PTD = new thread (showname); // defines a thread and the passed-in method with parameters.
02. PTD. isbackground = true;
03. PTD. Start ("lilei"); // reload the start method and PASS Parameters
Thread PTD = new thread (showname); // defines the thread and the passed-in method with parameters.
PTD. isbackground = true;
PTD. Start ("lilei"); // reload the start method and PASS Parameters

Method definition with parameters, parameter objec Type,

[CSHARP] view plaincopyprint?
01. // thread call with multiple parameters
02. Static void shownames (object names)
03 .{
04. List list = names as list;
05. foreach (string name in List)
06 .{
07. MessageBox. Show (name );
08 .}
09.
10 .}
// Thread call with multiple parameters
Static void shownames (object names)
{
List list = names as list;
Foreach (string name in List)
{
MessageBox. Show (name );
}

}

------------------------------------------------------------------------ The thread status is running -----------------------------------------------------------------------

At any time, the thread must be in a certain thread state.

The new thread starts its lifecycle in the unstarted state. The start method of the thread class remains in the unstarted State until it is called. After the method is called, it enters the started state, and immediately return the control of the program to the calling program (after the thread is called, you can do something else ). Then, the thread that calls the start method (that is, the started thread) and other threads in the program run concurrently.

Thread priority

Each thread has a priority in the range of threadpriority. Lowest and threadpriority. Highest. By default, the priority of each thread is normal.

Windows supports the concept of timeslicing. The idea is that threads with the same priority share a processor.

------------------------------------------------------------------------ Thread synchronization and class monitor failover -----------------------------------------------------------------------

Generally, multiple execution threads need to operate on shared data. If the thread with the right to access Shared data can only read data, it does not need to prevent multiple threads from simultaneously accessing shared data. However, when multiple threads share data and one or more threads need to modify data, unexpected results may occur. If one thread is updating data and the other thread tries to update the data, the data reflects the results after the second update operation.

Therefore, you can solve this problem by allowing only one thread to access the code used to operate shared data at a time. Other threads that want to operate data should wait. After a thread with exclusive access permission completes data operations, wait for the data of the Operation thread to continue. This is called mutex or thread synchronization.

C # provides two solutions:

1. Monitor class: main method (the parameter passed in by the method is an objec object, which is generally the thread currently called ):

Monitor. Enter (): gets the exclusive lock.

Monitor. Wait (): Release the lock on the object and stop the current thread until the lock is acquired again.

Monitor. Pulse (): indicates the change of the state of the thread object in the waiting queue.

Monitor. Exit (): Release the exclusive lock.

2. Lock Keyword:

Add a lock before the object:

Sample Code: monitor usage:

[CSHARP] view plaincopyprint?
01. Public class Mt
02 .{
03. Private int age;
04. Private int buff = 0; // buff determines whether the content has been updated or extracted. 0 indicates that the content has not been updated, and 1 indicates that the content has been updated.
05. Int age
06 .{
07. Get
08 .{
09. Monitor. Enter (this); // obtain the exclusive lock of this object
10. If (buff = 0) // wait for this thread if the content is empty or not updated
11 .{
12. MessageBox. Show ("the content is blank or not updated ");
13. Monitor. Wait (this); // release the lock and wait
14 .}
15. Buff --;
16. MessageBox. Show ("read content ");
17. Monitor. Pulse (this); // notifies the thread of the waiting queue. The object state needs to be changed.
18. Monitor. Exit (this); // release the exclusive lock
19. Return age;
20.
21 .}
22. Set
23 .{
24. Monitor. Enter (this );
25. If (buff = 1)
26 .{
27. MessageBox. Show ("the content has not been read ");
28. Monitor. Wait (this );
29 .}
30. Buff ++;
31. MessageBox. Show ("written content" + value );
32. Age = value;
33. Monitor. Pulse (this );
34. Monitor. Exit (this );
35 .}
36 .}
37 .}
Public class Mt
{
Private int age;
Private int buff = 0; // buff determines whether the content has been updated or extracted. 0 indicates that the content has not been updated, and 1 indicates that the content has been updated.
Int age
{
Get
{
Monitor. Enter (this); // obtain the exclusive lock of this object
If (buff = 0) // wait for this thread if the content is empty or not updated
{
MessageBox. Show ("the content is empty or not updated ");
Monitor. Wait (this); // release the lock and wait
}
Buff --;
MessageBox. Show ("read content ");
Monitor. Pulse (this); // notify the thread of the waiting queue. The status of this object needs to be changed.
Monitor. Exit (this); // release the exclusive lock
Return age;

}
Set
{
Monitor. Enter (this );
If (buff = 1)
{
MessageBox. Show ("the content has not been read ");
Monitor. Wait (this );
}
Buff ++;
MessageBox. Show ("written content" + value );
Age = value;
Monitor. Pulse (this );
Monitor. Exit (this );
}
}
}

Lock usage:

[CSHARP] view plaincopyprint?
01. // lock usage
02. Int age2
03 .{
04. Get
05 .{
06. Lock (this) // The start phase. The exclusive lock is obtained.
07 .{
08. If (buff = 0) // wait for this thread if the content is empty or not updated
09 .{
10. MessageBox. Show ("the content is blank or not updated ");
11. Monitor. Wait (this); // release the lock and wait
12 .}
13. Buff --;
14. MessageBox. Show ("read content ");
15. Monitor. Pulse (this); // notify the thread of the waiting queue. The object state needs to be changed.
16. Return age;
17.
18.} // end stage, exclusive lock released
19 .}
20. Set
21 .{
22. Lock (this)
23 .{
24. If (buff = 1)
25 .{
26. MessageBox. Show ("the content has not been read ");
27. Monitor. Wait (this );
28 .}
29. Buff ++;
30. MessageBox. Show ("written content" + value );
31. Age = value;
32. Monitor. Pulse (this );
33 .}
34 .}
35.
36 .}
// Lock usage
Int age2
{
Get
{
Lock (this) // The start phase. The exclusive lock is obtained.
{
If (buff = 0) // wait for this thread if the content is empty or not updated
{
MessageBox. Show ("the content is empty or not updated ");
Monitor. Wait (this); // release the lock and wait
}
Buff --;
MessageBox. Show ("read content ");
Monitor. Pulse (this); // notify the thread of the waiting queue. The status of this object needs to be changed.
Return age;

} // The exclusive lock is released at the end of the phase.
}
Set
{
Lock (this)
{
If (buff = 1)
{
MessageBox. Show ("the content has not been read ");
Monitor. Wait (this );
}
Buff ++;
MessageBox. Show ("written content" + value );
Age = value;
Monitor. Pulse (this );
}
}

}

----------------------------------------------------------------- Precautions for lock and monitor ------------------------------------------------------------------

Note: when using the enter and exit methods of the monitor class to manage the Lock of an object, you must call the exit method to release the lock. If an exception is thrown in a method before the exit method is called, and the exception is not caught, the method is terminated and the exit method is not called. Therefore, the lock is not released. To avoid this error, you can put the code that may cause the exception into a try module, and place the call to the exit method in the Finally block to ensure the lock is released.

You can use a lock block to manage the lock on the synchronization object and avoid forgetting to call the exit method of the monitor class to release the lock. When lock is terminated for some reason, C # implicitly calls the exit method of the monitor class. In this way, the lock can be released even if an exception occurs in the code.

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.