C # intermediate-commonly used multi-threaded operations (Continuous updates ),

Source: Internet
Author: User

C # intermediate-commonly used multi-threaded operations (Continuous updates ),

I. Preface

Multi-threaded operations have always been a common operation in programming. Mastering Basic operations can make the program run more effectively. This article does not mean big but comprehensive. It just classifies and summarizes the multi-threaded operations that are often used in my work. You can also check it when your memory is poor. This article draws on several wonderful blog posts in the garden. At the end of the article, I will post the specific sources and thank them for their selfless dedication.

 

Ii. About threads

(1)Why use thread:

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

You can use threads to simplify encoding;

You can use threads for concurrent execution.

(2)Processes, application domains, and threads:

Process is a basic concept in Windows. It contains the resources required to run a program. Processes are relatively independent. A process cannot access the data of another process (unless in distributed computing mode). Failure of one process does not affect the running of other processes, in Windows, work is divided into multiple independent regions by processes. A process can be understood as the basic boundary of a program.

The application domain (AppDomain) is the logical area where the program runs. It can be considered as a lightweight process ,.. NET Assembly runs in the application domain. A process can contain multiple application domains, and an application domain can contain multiple assemblies. When one application domain contains one or more context, the context CLR can be used to place the statuses of some special objects in different containers.

A Thread is a basic execution unit in a process. The first Thread executed at the process entry is considered as the main Thread of the process.

The diagram is as follows:

Iii. Thread

Thread may be the most commonly used multi-threaded class except Task. General Usage:

// One threadThread thread = new ThreadStart (functiion); thread. start (); // thread. joinThread ThreadA = new Thread (delegate () {// do something}); Thread ThreadB = new Thread (delegate () {// do something; ThreadA. join (); // do another thing}); // start the ThreadA thread. start (); ThreadB. start (); // At the beginning, the two threads run alternately. When thread B runs to the join Operation of thread A, thread A is executed first, and thread B continues to execute. You can understand that the two are not mutually exclusive at first. When the join operation is performed, thread a is overtaking thread B.

 

4. ThreadPool

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.

If a thread takes a very long time, there is no need to use the thread pool (not long operations, but not suitable .), Besides, we cannot control the start, suspension, and suspension of threads in the thread pool.

ThreadPool.QueueUserWorkItem(function,parameter);

 

V. Task

Task is the most commonly used multi-threaded method. The general method is as follows:

// one taskvar task = new Task(() =>{
// do something
});task.Start();
// task one by one
var task = new Task(() =>{
 // do something  
});

Task task2 = task.ContinueWith(()=>{
// do something  
});
task.Start();

// Define tasksvar tasks = new Task [PackCount]; // multithread Task for (int index = 0; index <PackCount; index ++) {int Threadindex = index; var task = new Task () =>{// do something}); tasks [Threadindex] = task; task. start ();} Task. waitAll (tasks); // wait for all threads to complete // Task. waitAny (tasks); // wait for a thread to finish executing the main program

// Task. Factory
Task. Factory. StartNew () =>{// do something });

 

6. Invoke, BeginInvoke, and DynamicInvoke

The main note here is the various Invoke under delegate

Invoke)

Delegate void MyDelegate (); MyDelegate del = new MyDelegate (Function); del. Invoke (); // use the delegate's invoke Method

 

BeginInvoke (it captures an idle thread from the thread pool to delegate the execution method)

Case A: Use IAsyncResult. IsCompleted to determine whether the Sub-thread has completed execution

delegate T MyDelegate();MyDelegate del = new MyDelegate(Function);IAsyncResult result = del.BeginInvoke(parameter,null,null);//if the branch thread is not completedwhile(!result.IsCompleted)  {    // the main thread do another thing}T data = del.EndInvoke(result); // var data is the result of Function with parameter

 

B: Use IAsyncResult. AsyncWaitHandle. WaitOne (timeout) to determine whether the Sub-thread has completed execution

delegate T MyDelegate();MyDelegate del = new MyDelegate(Function);IAsyncResult result = del.BeginInvoke(parameter,null,null);//if the branch thread is not completedwhile(!result.AsyncWaitHandle.WaitOne(int timeout))  {    // the main thread do another thing}T data = del.EndInvoke(result); // var data is the result of Function with parameter

 

C: Use WaitHandle. WaitAll (WaitHandle [], timeout) to determine whether the Sub-thread has completed execution

delegate T MyDelegate();MyDelegate del = new MyDelegate(Function);IAsyncResult result = del.BeginInvoke(parameter,null,null);WaitHandle[] waitHandleList = new WaitHandle[] { result.AsyncWaitHandle,........ };while (!WaitHandle.WaitAll(waitHandleList,int timeout)){    // the main thread do another thing}T data = del.EndInvoke(result); // var data is the result of Function with parameter

 

D: It is very troublesome to use the polling method to check the status of the asynchronous method, and the efficiency is not high. Therefore, a callback function is required. The main thread can do its own thing with peace of mind, and the asynchronous thread can execute the callback function after completing the operation. The callback function is still on the asynchronous thread rather than the main thread.

delegate T MyDelegate();MyDelegate del = new MyDelegate(Function);IAsyncResult result = del.BeginInvoke(parameter,new AsyncCallback(callbackFunction),object);....MainThread do somethng...static void callbackFunction(IAsyncResult result){     AsyncResult  _result = (AsyncResult )result;     MyDelegate del = (MyDelegate)_result.AsyncDelegate;     T data = del.EndInvoke(_result);     T1 objectReciever = (T1)result.AsyncResult; //object=result.AsyncResult}

 

DynamicInvoke:

Similar to Delegate. Invoke, the only difference between synchronization and the same thread is that it uses the later binding method to call the Delegate method, so the time is too costly.

Working instance: An exception occurs in WPF:"The Calling thread cannot access this object because another thread owns this object."

Case A: If the code for this exception is in The xaml. cs file, then Dispatcher. Invoke is enough.

Case B: If the code for this exception is in the. cs file, there is a trick in Stack Overflow:

1 private void RaiseEventOnUIThread (Delegate theEvent, object [] args) 2 {3 foreach (Delegate d in theEvent. getInvocationList () 4 {5 ISynchronizeInvoke syncer = d. target as ISynchronizeInvoke; 6 if (syncer = null) // The static function is null.
7 {8 d. dynamicInvoke (args); 9} 10 else11 {12 syncer. beginInvoke (d, args); // asynchronously execute the delegate 13} 14} 15} on the thread where the object is created}

References:

[1] http://blog.sina.com.cn/s/blog_5a6f39cf0100qtzf.html

[2] http://www.cnblogs.com/slikyn/articles/1525940.html

[3] http://kb.cnblogs.com/page/130487/#t3

[4] http://blog.csdn.net/soft_123456/article/details/38819877

【5】 http://www.cnblogs.com/laoyur/archive/2011/04/14/2016025.html

[6] http://blog.csdn.net/cselmu9/article/details/8274556

【7】 http://stackoverflow.com/questions/1698889/raise-events-in-net-on-the-main-ui-thread

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.