C # multithreading,

Source: Internet
Author: User

C # multithreading,

C # Multithreading

I. Reasons for using threads

1. You can use threads to isolate code from other codes to improve application reliability.

2. You can use threads to simplify encoding.

3. Threads can be used for concurrent execution.

Ii. Basic Knowledge

1. Process and thread: as the basic unit of operating system execution programs, a process has application resources, processes include threads, process resources are shared by threads, and threads do not have resources.

2. Foreground Thread and background Thread: the foreground Thread is created by default through the Thread class. When all foreground threads are closed, all background threads are terminated directly without throwing an exception.

3. Suspend and Resume: As the thread execution sequence and program execution conditions are unpredictable, suspension and wakeup are prone to deadlocks, it should be used as little as possible in practical applications.

4. Blocking thread: Join, blocking the calling thread until the thread ends.

5. Terminate the thread: Abort: throws a ThreadAbortException exception to terminate the thread. The terminated thread cannot be awakened. Interrupt: throws a ThreadInterruptException exception to terminate the thread. By capturing exceptions, the thread can continue execution.

6. thread priority: AboveNormal BelowNormal Highest Lowest Normal. The default value is Normal.

Iii. Use of threads

A thread function can be passed through delegation without parameters or parameters (only one parameter is allowed). It can be encapsulated with a class or struct.

Namespace Test {class Program {static void Main (string [] args) {Thread t1 = new Thread (new ThreadStart (TestMethod )); thread t2 = new Thread (new ParameterizedThreadStart (TestMethod); t1.IsBackground = true; t2.IsBackground = true; t1.Start (); t2.Start ("hello"); Console. readKey ();} public static void TestMethod () {Console. writeLine ("thread function without Parameters");} public static void TestMethod (object data) {string datastr = data as string; Console. writeLine ("thread function with parameters, parameter: {0}", datastr );}}}

4. Thread Pool

Because thread creation and destruction require a certain amount of overhead, excessive use of threads will cause a waste of memory resources. For performance considerations, the concept of thread pool is introduced. The thread pool maintains a request queue. The code in the thread pool extracts tasks from the queue and delegates them to a thread in the thread pool for execution. The thread will not be destroyed immediately after execution, in this way, tasks can be executed in the background, and the overhead of thread creation and destruction can be reduced.

The thread pool thread is the background thread (IsBackground) by default ).

Namespace Test {class Program {static void Main (string [] args) {// Add a work item to the thread pool queue. A thread parameter ThreadPool can be passed here. queueUserWorkItem (TestMethod, "Hello"); Console. readKey ();} public static void TestMethod (object data) {string datastr = data as string; Console. writeLine (datastr );}}}

V. Task Type

It is easy to use the ThreadPool QueueUserWorkItem () method to initiate an asynchronous thread execution, but the biggest problem with this method is that there is no built-in mechanism to let you know when the operation will be completed, is there a built-in mechanism to obtain a return value after the operation is complete. Therefore, you can use the Task class in System. Threading. Tasks.

Construct a Task <TResult> object and pass the return type of an operation to the generic TResult parameter.

Namespace Test {class Program {static void Main (string [] args) {Task <Int32> t = new Task <Int32> (n => Sum (Int32) n ), 1000); t. start (); t. wait (); Console. writeLine (t. result); Console. readKey ();} private static Int32 Sum (Int32 n) {Int32 sum = 0; for (; n> 0; -- n) checked {sum + = n ;} // The result is too large. An exception is thrown: return sum ;}}}

When a task is completed, a new task is automatically started.
After a task is completed, it can start another task. The previous code is rewritten below, without blocking any threads.

Namespace Test {class Program {static void Main (string [] args) {Task <Int32> t = new Task <Int32> (n => Sum (Int32) n ), 1000); t. start (); // t. wait (); Task cwt = t. continueWith (task => Console. writeLine ("The result is {0}", t. result); Console. readKey ();} private static Int32 Sum (Int32 n) {Int32 sum = 0; for (; n> 0; -- n) checked {sum + = n ;} // result overflow, throwing an exception return sum ;}}}

6. Delegate asynchronous execution

Asynchronous call of delegation: BeginInvoke () and EndInvoke ()

Namespace Test {public delegate string MyDelegate (object data); class Program {static void Main (string [] args) {MyDelegate mydelegate = new MyDelegate (TestMethod); IAsyncResult result = mydelegate. beginInvoke ("Thread Param", TestCallback, "Callback Param"); // string resultstr = mydelegate is executed asynchronously. endInvoke (result);} // The thread function public static string TestMethod (object data) {string datastr = data as string; return datastr ;} // asynchronous callback function public static void TestCallback (IAsyncResult data) {Console. writeLine (data. asyncState );}}}

VII. Thread Synchronization

1) Interlocked: all methods perform an atomic read or write operation.

2) lock () Statement: avoid locking the public type. Otherwise, the instance will be out of the control range of the Code and the private object will be defined to lock the instance.

3) Monitor for Thread Synchronization

You can use Monitor. Enter () and Monitor. Exit () to obtain and release the exclusive lock. After obtaining the lock, the resource is exclusively occupied and other threads are not allowed to access the lock.

There is also a TryEnter method, which does not block the wait when the resource cannot be requested. You can set the timeout time and return false if the resource cannot be obtained.

4) ReaderWriterLock

When the number of read and write operations on resources is small, in order to improve resource utilization, the read operation lock is a shared lock, multiple threads can read resources concurrently, and the write operation is an exclusive lock, only one thread is allowed.

5) synchronize events

There are two types of events: the termination status and the non-termination status. When the WaitOne is called, the request is successful and the time status is Set to the termination status through Set.

1) AutoResetEvent (auto reset event)

2) ManualResetEvent (manual reset event)

6) semaphores (Semaphore)

Semaphore is an int variable maintained by the kernel object. When it is 0, the thread is blocked. When it is greater than 0, the semaphore is lifted. When the waiting thread on a semaphore is blocked, the semaphore count is + 1.

The thread uses WaitOne to reduce the semaphores by 1, and uses Release to increase the semaphores by 1, which is easy to use.

7) Mutex)

Exclusive resource, similar to Semaphore.

8) Cross-Process Synchronization

System-level synchronization can be achieved by setting the name of the synchronization object. Different applications identify different synchronization objects by the name of the synchronization object.

 

 

Author: arfan Lu Source: Lu.

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.