Whether we use Thread,threadpool,task or APM asynchronously, we are using multithreading in essence. For the novice, do not dare to use multi-threaded reasons, as far as my personal experience, is the multi-threaded abnormal capture mode or lack of understanding of the timing, and once the exception is not captured, will bring difficult to find the bug, resulting in a system crash. And multithreading itself is not overnight can learn, must continue to learn to summarize, so I personally think you want to use a threading model, first of all it has enough knowledge, especially for the exception of the capture. If you are not fully confident, it is best to use multithreading sparingly in real-world development.
1,APM Asynchronous programming model.
Use BeginXxx and EndXxx methods. With regard to the catch of the exception, the asynchronous operation may not have entered the queue for the exception that was just called beginxxx. This exception can generally be ignored. For exceptions that occur when an asynchronous operation is entered, the error is placed in the IAsyncResult object, and when we call the EndXxx method, the error code is converted to an appropriate exception to be thrown again. So for the APM programming model, we only use the EndXxx method to catch the exception. Pseudo code:
Try { Result = someobj.endxxx (IAsyncResult);} Catch (xxxexception e) {//exception handling}
Precautions:
1) The call to the EndXxx method is necessary, otherwise it may cause a resource leak, even though you may not care about the return result of the asynchronous call, remember to call this method.
2) Only one endxxx method can be called.
3) Call the EndXxx method to always use the same object as when BeginXxx. The reference here is to distinguish between references, which are treated as different objects. For delegate to add, even delegates of the same signature, which are compiled into specific classes by the compiler, have different class names.
4) asynchronous operations that cannot cancel asynchronous I/O throttling. Do not superstition this sentence, he said is I/O operation, refers to a request action, if we are multiple requests, such as the asynchronous block upload file, can do the cancellation function.
5) There are many I/O operation classes in the FCL that implement APM. such as classes derived from System.IO.Stream, Socket,dns,webrequest, SqlCommand and so on. They all provide the beginxxx and EndXxx methods.
6) You can use APM to execute any method, we only need to define a delegate,delegate that is consistent with the method signature will generate a BeginInvoke and EndInvoke method to support APM operations.
2,thread & ThreadPool
The disadvantage of thread and ThreadPool initiating async:
1) There is no built-in mechanism to know when a task is completed.
2) Unable to get the return value of the task.
Thread is too expensive to use threadpool unless you want to show that your thread is the foreground thread or to set a priority on the thread, otherwise do not use thread.
Note: The thread pool is shared by all the AppDomain. A CLR maintains a thread pool.
3,task
The introduction of task solves the above two problems.
1) Task can wait for the task to complete through the Wait () method. This method is blocked.
2) The return result can be obtained by Task.result. The wait method is called inside result, so the query property is blocked.
3) For unhandled exceptions of task functions, they are wrapped into aggregateexception exceptions. You can capture the wait () method and the result property. Specific exceptions can be queried further through AggregateException's innerexceptions.
4) The static method of the task WaitAny and WaitAll can wait for multiple tasks to return. You can also catch exceptions for both methods.
5) for cases where wait,result,exception are not called to query for unhandled exceptions, for example: Only the Task.start method is called. When the task object is reclaimed, the Finalize method throws the exception termination process again. You can register a method with the Taskscheduler.unobservedtaskexception event to handle such exceptions. By Unobservedtaskexceptioneventargs The Setobserved method, you can ignore this exception so that the process does not terminate.
6) When constructing a task, you can pass the CancellationToken object to support cancellation. If it is a task function, the type is operationcanceledexception by calling cancellationtoken.throwifcancellationrequested thrown by the exception. If the task function does not pass the CancellationToken object, the exception thrown is taskcanceledexception, which is equivalent to a task-level cancellation.
7) The ContinueWith method of the task can open a second task when the first task is completed. This is a powerful feature, and the ContinueWith method does not block the calling thread, it is asynchronous. We can write an event callback method in ContinueWith, which can act as an event completion notification. But it can only receive notification of task completion, to achieve update notification of task progress, so far, the task is still not done.
task<int> t = new task<int> (() = Sum (+)); T.start (); T.continuewith (Task = Console.WriteLine ("Result:" + task.) Result), taskcontinuationoptions.onlyonrantocompletion); T.continuewith (Task = Console.WriteLine ("Canceled"), taskcontinuationoptions.onlyoncanceled); T.continuewith (Task = Console.WriteLine ("Failed"), taskcontinuationoptions.onlyonfaulted);
For this channeling code above, if there is an unhandled exception, it will also cause the process to terminate. You can also use the Taskscheduler.unobservedtaskexception event to register a method to handle.
8) A task can specify a subtask, the subtasks are not completed, and the continuetask of the parent task is not executed. The exception is the same as in the above procedure. Because this is also non-blocking, unhandled exceptions can only be processed in the taskscheduler.unobservedtaskexception for the time being.
task<int32[]> parent = new Task<int[]> (() = { int32[] result = new Int32[3]; New Task<int32> (() = result[0] = Sum (+), taskcreationoptions.attachedtoparent). Start (); New Task<int32> (() = result[1] = Sum ($), taskcreationoptions.attachedtoparent). Start (); New Task<int32> (() = result[2] = Sum (+), taskcreationoptions.attachedtoparent). Start (); return result; }); Parent. ContinueWith (Parenttask = Array.foreach (parenttask.result, num = Console.WriteLine (num))); Parent. Start ();
9) Taskfactroy can simplify the creation of a set of similar tasks.
Task parent = new Task (() = {CancellationTokenSource cts = new Cancellationtokensou Rce (); taskfactory<int32> tf = new taskfactory<int32> (CTS. Token, Taskcreationoptions.attachedtoparent, taskcontinuationoptions.executesynchronously, TaskSche Duler. Default); Create three child task var childtasks = new[]{TF. StartNew (() =>sum (CTS. token,100)), TF. StartNew (() =>sum (CTS. token,200)), TF. StartNew (() =>sum (CTS. Token,int32.maxvalue))}; When one failed,cancel the other for (int i = 0; i < childtasks.length; i++) { Childtasks[i]. ContinueWith (task = cts. Cancel (), taskcontinuationoptions.onlyonfaulted); }//display the MaxValue TF. ContinuewhenaLL (childtasks, completetasks = completetasks.where (task =!tas K.iscanceled &&!task. isfaulted). Max (t = t.result), cancellationtoken.none). ContinueWith (Task = Console.WriteLine ("The Max is:" + task.) Result)); }); Show exception parent. ContinueWith (P = = {StringBuilder sb = new StringBuilder (); Sb. Appendline ("Error occours:"); foreach (Var e in P.exception.flatten (). innerexceptions) {sb. Appendline (E.message); } Console.WriteLine (sb.) ToString ()); }, taskcontinuationoptions.onlyonfaulted); Parent. Start ();
4, for collaboration cancellation to use the CancellationTokenSource class.
1) Cancellationtokensource.token method returns CancellationToken, you can pass CancellationToken to our working methods, and query Cancellationtoken.iscancellationreq The Uested property to obtain whether the operation was canceled. In the case of cancellation, you can end the working method.
2) The cancellation method is generally called on the main thread. Cancellationtoeknsource.cancel.
3) cancellation can be added to the callback method, through the Cancellationtoken.register method registration. For exceptions thrown by the callback method, you can catch the Cancel method, the exception is wrapped into the aggregateexception exception, and the details of the exception that queries the innerexceptions can be queried.
4) CancellationTokenSource static method Createlinkedtokensource can create an associated Createlinkedtokensource object. Any one of the Createlinkedtokensource is canceled and the associated Createlinkedtokensource is canceled.
5, Task Scheduler.
is divided into thread pool Task Scheduler (thread Pool Task Scheduler) and synchronization Context Task Scheduler (Synchroliazation Context Task Scheduler). The synchronization Context Task Scheduler can dispatch all tasks to the UI thread, which is useful for updating the interface's asynchronous operations! The default scheduler is the thread pool Task Scheduler.
Non-UI thread update UI interface will error, you can specify the synchronization context Task Scheduler using the following method:
TaskScheduler Syncsch = Taskscheduler.fromcurrentsynchronizationcontext (); task<int> t = new task<int> (() = Sum (+)); Update UI with SynchronizationContext t.continuewith (task = Text = task. Result.tostring (), Syncsch); T.start ();
6, summary of how non-UI threads update the UI interface
See my other article:
Http://www.cnblogs.com/xiashengwang/archive/2012/08/18/2645541.html
7,parallel
This class provides a For,foreach,invoke static method. It encapsulates the task class internally. Mainly used for parallel computing.
private void ParallelTest2 () {for (int i = 1; i < 5; i++) { Console.WriteLine (DoWork (i)); } Equivalent to the above code, but is multithreaded parallel execution, note here that the end index does not contain 5 var PLR = parallel.for (1, 5, I = Console.WriteLine (DoWork (i))); } private int DoWork (int num) { int sum = 0; for (int i = 0; I <= num; i++) { sum + = i; } return sum; }
Thread Periodic summary--apm,threadpool,task,taskscheduler, CancellationTokenSource