C # asynchronous programming 3 TPL Task asynchronous program development,
. Net added the task parallel library in Framework4.0, which makes it easier for developers to use multi-core and multi-threaded CPU environments. TPL is meeting the technical requirements of our series. Because TPL involves a lot of content and this series of articles are developed for asynchronous programs, this article does not cover all TPL content. I will write a Blog of the TPL series later. You may take a look.
TASK
Basic Task of TPL, which is the smallest unit of parallel programming of TPL, that is, an asynchronous operation. Asynchronous programming using tasks is very simple:
Static void Main (string [] args) {BaseTaskDemo (); // BaseTaskDemo2 (); // Console with the same effect. writeLine (String. format ("Main Thread: {0}, get asynchronous execution result: {1}", Thread. currentThread. managedThreadId, task. result); Console. readLine ();} private static void BaseTaskDemo () {var task = new Task () => {Thread. sleep (1, 2000); Console. writeLine (String. format ("Task Thread: {0}", Thread. currentThread. managedThreadId) ;}); task. start ();} private static void BaseTaskDemo2 () {var task = Task. run () => {Thread. sleep (1, 2000); Console. writeLine (String. format ("Task Thread: {0}", Thread. currentThread. managedThreadId ));});}
Program description:
1. new Task (Action) creates an asynchronous Task. The parameter Action is the delegate object to be executed by the asynchronous Task.
2. task. Start () starts the execution of asynchronous tasks.
3. Task. Run (Action) is equivalent to a combination of 1 and 2.
The preceding example program implements asynchronous operations, but the main thread cannot know whether the asynchronous task is completed or not. To obtain the execution result of a Task, the preceding program is modified as follows:
Static void Main (string [] args) {var task = TaskForResult (); Console. writeLine (String. format ("Main Thread: {0}", Thread. currentThread. managedThreadId); task. wait (); if (task. isCompleted) Console. writeLine (String. format ("Get asynchronous execution result: {0}", task. result); Console. readLine ();} private static Task <int> TaskForResult () {var task = Task. run () => {Thread. sleep (1, 2000); Console. writeLine (string. format ("Task thread :{ 0}. Task execution is complete. ", Thread. CurrentThread. ManagedThreadId); return 10 ;}); return task ;}
Program description:
1. the prototype of the following code is Task. run (Func <int>), the Run parameter is no longer Action, because in this task we want to return an int value, so we should use the Run (Func <T>) overload.
Var task = Task. Run () => {Thread. Sleep (2000); Console. WriteLine (string. Format ("Task Thread: {0}, Task execution completed. ", Thread. CurrentThread. ManagedThreadId); return 10 ;});
2. When task. Wait () is called in the main thread, the main thread will Wait until the asynchronous task is completed or canceled.
3. The task. IsCompleted attribute is used to determine whether the asynchronous task is completed.
4. task. Result: Obtain the execution Result (return value) of the asynchronous task)
The preceding sample program has implemented the main thread to obtain the state and return value of the asynchronous program. However, if the asynchronous program is very time-consuming, the main thread needs to temporarily cancel the time-consuming asynchronous program execution function. To meet the above requirements, the program can be adjusted as follows:
Static void Main (string [] args) {CancellationTokenSource tokenSource = new CancellationTokenSource (5000); var task = TaskForResult2 (tokenSource); Console. writeLine (String. format ("Main Thread: {0}", Thread. currentThread. managedThreadId); Console. writeLine (String. format ("Main Thread: {0}, get asynchronous execution result: {1}", Thread. currentThread. managedThreadId, task. result); Console. readLine ();} private static Task <int> TaskFor Result2 (CancellationTokenSource tokenSource) {var task = Task. Run () ==>{ Thread. Sleep (10000); if (! TokenSource. IsCancellationRequested) {Console. WriteLine (String. Format ("Task thread: {0}, Task 1 completed. ", Thread. CurrentThread. ManagedThreadId); return 10 ;}else {return-1 ;}, tokenSource. Token); return task ;}
Program description:
1. CancellationTokenSource provides the task cancellation message. The constructor 5000 indicates that the CancellationTokenSource times out and is canceled after being sent for 5s.
2. In the Task delegate, tokenSource. IsCancellationRequested obtains the unmark.
3. The task. Result implicitly calls the Wait () method.
If an exception occurs during asynchronous Task execution, you need to respond to the exception:
Static void Main (string [] args) {CancellationTokenSource tokenSource = new CancellationTokenSource (5000); var task = TaskForResult2 (tokenSource); Console. writeLine (String. format ("Main Thread: {0}", Thread. currentThread. managedThreadId); try {// task. wait (); Console. writeLine (String. format ("Main Thread: {0}, get asynchronous execution result: {1}", Thread. currentThread. managedThreadId, task. result);} catch (aggresponexception ex ){} Console. readLine ();} private static Task <int> TaskForResult2 (CancellationTokenSource tokenSource) {var task = Task. run () => {Thread. sleep (1000); if (! TokenSource. IsCancellationRequested) {throw new Exception ("throw Exception");} else {return-1 ;}, tokenSource. Token); return task ;}
Program description:
1. Exceptions thrown in tasks must be captured in Task. Wait () or task. Result.
After writing: The functions of tasks are far more than the above. Knowledge about Task multi-Task serialization, TaskFactory, and Paralle is very interesting and important. If you are interested, you can follow my subsequent TPL articles.