Multi-thread programming learning notes-parallel task library (2), multi-thread programming learning notes
Multi-thread programming learning notes-parallel task library (I)
3. Combined tasks
This example shows how to set mutually dependent tasks. We learn how to create a subtask of a task. This subtask must be executed after the execution of the parent task is completed.
1. The sample code is as follows:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace ThreadTPLDemo {class Program {static void Main (string [] args) {Console. writeLine ("Task Combination Operation ----"); Task <string> task1 = CreateTask ("Task1", 3); Task <string> task2 = CreateTask ("Task2", 2 ); // create a continuation operation (sub-operation) task1.ContinueWith (t => Console for Task 1. writeLine ("task1 suboperation: {0}, thread ID: {1}, is it a thread in the thread pool: {2 }",
T. result, Thread. currentThread. managedThreadId, Thread. currentThread. isThreadPoolThread), TaskContinuationOptions. onlyOnRanToCompletion); task1.Start (); task2.Start (); Thread. sleep (TimeSpan. fromSeconds (4); Task task3 = task2.ContinueWith (t => Console. writeLine ("task2 suboperation: {0}, thread ID: {1}, is it a thread in the thread pool: {2 }",
T. Result, Thread. CurrentThread. ManagedThreadId, Thread. CurrentThread. IsThreadPoolThread ),
TaskContinuationOptions. onlyOnRanToCompletion | TaskContinuationOptions. executeSynchronously); task3.GetAwaiter (). onCompleted () => Console. writeLine ("task3 Asynchronous Operation completed, thread ID: {0}, is it a thread in the thread pool: {1 }",
Thread. currentThread. managedThreadId, Thread. currentThread. isThreadPoolThread); Thread. sleep (TimeSpan. fromSeconds (2); Console. writeLine ("-------------- Parent and Child tasks ------------"); var task5 = new Task <string> () => {var task6 = Task. factory. startNew () => taskdetail( "subtask Task6", 5), TaskCreationOptions. attachedToParent); task6.ContinueWith (t => taskith ("delayed operation task7", 2), TaskContinuationOptions. attachedToParen T); return task1_( "task5", 2) ;}); task5.Start (); while (! Task5.IsCompleted) {Console. writeLine ("task5 status -- {0}", task5.Status); Thread. sleep (500);} Console. writeLine ("-- task5 status-{0}", task5.Status); string result = task5.Result; Console. writeLine ("task5 running result -- {0}", result); Console. readKey ();} private static string taskdetail( string name, int seconds) {Console. writeLine ("Task Thread ID: {0}, is it a Thread in the Thread pool: {1}, name: {2}", Thread. currentThread. managedThreadId, Thread. currentThread. isThreadPoolThread, name); Thread. sleep (TimeSpan. fromSeconds (seconds); return string. format ("Thread ID: {0}, name: {1}: Second: {2}", Thread. currentThread. managedThreadId, name, seconds);} static Task <string> CreateTask (string name, int seconds) {return new Task <string> () => taskdetail( name, seconds ));}}}
2. The program running result is shown in.
As shown in the results, the program creates two tasks task1 and task2 at startup, and creates a suboperation for the first task. Start the two tasks, wait for 4 seconds, run the sub-operation for Task 2, and run the sub-operation synchronously using the TaskContinuationOptions. OnlyOnRanToCompletion option. If the running time of sub-operations is very short, the above method is very useful, because running in the main thread is faster than running in the thread pool.
If we comment out the code waiting for 4 seconds (in blue), Task 2 will be put into the thread pool, as shown in.
Next, we define a suboperation task3 for the suboperation of Task 2, and use the new GetAwaiter and Oncompleted methods for Task 3 to execute a subsequent operation.
Finally, we created a new task task5 and run a subtask task6 and task7 in the TaskContinuationOptions. AttachedToParent option.
4. Convert APM mode to task
In this example, the previous article (multi-threaded programming learning note-Thread Pool (1) is converted into a task (in this example, the delegate is called in the thread pool. The key to converting APM to TPL is the Task <T>. Factory. FromAsync () method.
1. The Code is as follows:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace ThreadTPLDemo {public delegate string AsyncTaskRun (string name); public delegate string IncompAsyncTaskRun (out int threadId); class Program {static void Main (string [] args) {Console. writeLine ("converts APM mode to Task... "); Int threadId = 0; AsyncTaskRun tkDele = RunTask; IncompAsyncTaskRun taskDele = RunTask; Console. writeLine ("-------- 1 ------------"); Task <string> task1 = Task <string>. factory. fromAsync (tkDele. beginInvoke ("task1", Callback, "Task asynchronous call Callback function"), tkDele. endInvoke); task1.ContinueWith (t => Console. writeLine ("Task 1 callback function execution ends and subsequent sub-operations are performed: {0}", t. result); while (! Task1.IsCompleted) {Console. writeLine ("task1 status -- {0}", task1.Status); Thread. sleep (500);} Console. writeLine ("-- task1 status-{0}", task1.Status); Thread. sleep (1, 2000); Console. writeLine (); Console. writeLine ("--------------- 2 -------------"); Task <string> task2 = Task <string>. factory. fromAsync (tkDele. beginInvoke, tkDele. endInvoke, "task2", "Callback Function asynchronously called by Task"); task2.ContinueWith (t => Console. writeLine ("task2 After the callback function is executed, perform the following sub-operations: {0} ", t. Result); while (! Task2.IsCompleted) {Console. writeLine ("task2 status -- {0}", task2.Status); Thread. sleep (500);} Console. writeLine ("-- task2 status-{0}", task2.Status); Thread. sleep (1, 2000); Console. writeLine (); Console. writeLine ("--------------- 3 -------------"); IAsyncResult r = taskDele. beginInvoke (out threadId, Callback, "Call Callback function asynchronously in the thread pool"); Task <string> task3 = Task <string>. factory. fromAsync (r, _ => taskDele. endInvoke (out thr EadId, r); task2.ContinueWith (t => Console. writeLine ("Task 3 callback function execution ends, subsequent sub-operations: {0}, thread ID: {1}", t. result, threadId); while (! Task2.IsCompleted) {Console. writeLine ("task3 status -- {0}", task2.Status); Thread. sleep (500);} Console. writeLine ("-- task3 status-{0}", task2.Status); Thread. sleep (1, 2000); Console. writeLine ("----------------------------"); Thread. sleep (1, 2000); Console. read ();} private static void Callback (IAsyncResult r) {Console. writeLine ("start to call the callback function... "); Console. writeLine ("Status of the callback function at this time: {0}", r. asyncState); Console. writeLine ("Whether the Thread that calls this callback function is in the Thread pool: {0}", Thread. currentThread. isThreadPoolThread); Console. writeLine ("the ID of the Thread that calls this callback function in the Thread pool: {0}", Thread. currentThread. managedThreadId);} private static string RunTask (string name) {Console. writeLine ("Getting started... "); Console. writeLine ("Whether the Thread that calls this callback function is in the Thread pool: {0}", Thread. currentThread. isThreadPoolThread); Thread. sleep (TimeSpan. fromSeconds (2); Thread. currentThread. name = name; int threadId = Thread. currentThread. managedThreadId; return string. format ("ID of this Thread: {0}, name {1}", threadId, Thread. currentThread. name);} private static string RunTask (out int threadId) {Console. writeLine ("Getting started... "); Console. writeLine ("Whether the Thread that calls this callback function is in the Thread pool: {0}", Thread. currentThread. isThreadPoolThread); Thread. sleep (TimeSpan. fromSeconds (2); threadId = Thread. currentThread. managedThreadId; return string. format ("ID of the thread in the thread pool: {0}", threadId );}}}
2. The program running result is shown in.
It can be seen from the program running result that IAsyncResult and Func <IAsyncResult, string> are directly input in Task 1, and Task 1 executes the asynchronous call of the Delegate, which is normal.
Like task1, Task2 only uses different FromAsync method overloading. This overload does not allow you to specify a callback function that will be called after the asynchronous call is complete. In this example, the callback function is replaced by subsequent operations. If you must use a callback function, you can use a call method similar to task1.
Task3 we use a technique to call a delegate that is not compatible with FromAsync. We encapsulate EndInvoke into a lambda expression to adapt to the FromAsync method.
5. Convert the EAP mode to a task
In this example, convert (using the BackgroundWorker component example) in the previous article (multithread programming learning note-Thread Pool (3) to a task.
This example shows how to asynchronously convert an event to a TASK to run the TASK. The key in this example is to use TaskCompletionSource <T>, and T is the type of asynchronous operation result.
Using System; using System. collections. generic; using System. componentModel; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace ThreadPoolDemo {class Program {static void Main (string [] args) {Console. writeLine ("converts EAP mode to Task... "); Var tcs = new TaskCompletionSource <int> (); var worker = new BackgroundWorker (); worker. doWork + = (sender, eventArgs) => {eventArgs. result = RunTask ("background thread 1", 5) ;}; worker. runWorkerCompleted + = (sender, eventArgs) => {if (eventArgs. error! = Null) {Console. writeLine ("-- error-{0}", eventArgs. error); tcs. setException (eventArgs. error);} else if (eventArgs. cancelled) {Console. writeLine ("-- Cancel-"); tcs. setCanceled (); // cancel} else {Console. writeLine ("-- set the result value-{0}", eventArgs. result); tcs. setResult (int) eventArgs. result) ;}}; worker. runWorkerAsync (); int result = tcs. task. result; Console. writeLine ("-- Task running result-{0}", result); Thread. sleep (1, 2000); Console. read ();} private static int RunTask (string name, int seconds) {Console. writeLine ("Task {0} is running in Thread = {1}, whether it is in Thread pool: {2}", name, Thread. currentThread. managedThreadId,
Thread. CurrentThread. IsThreadPoolThread); Thread. Sleep (TimeSpan. FromSeconds (seconds); return 42 * seconds ;}}}
2. The program running result is shown in.
Note: tcs. SetResult should be closed in try-catch to facilitate exception acquisition. Alternatively, you can use tcs. TrySetResult.