C # multithreaded programming (3)--turn on subtasks

Source: Internet
Author: User

I explained the await and async keywords, the purpose of these two keywords is to encapsulate the part of the async-qualified method that follows the await keyword into a delegate that executes after the await-decorated task finishes. Simply put, wait for the task to complete, the subsequent program executes, and the wait does not cause the thread to block. The key is that the program will continue to be delivered to the main thread after the task is completed. Next, I'll show you how to execute the method with a new task after the task has finished executing.

Not much nonsense on, on the code, let's see how the thread pool continues to complete other methods after the task has ended.

1 Static voidMain (string[] args)2 {3 RunAsync ();4Console.WriteLine ("Async Run");5 Console.read ();6 }7  Public Static voidRunAsync ()8 {9     varTask = Task.run (() =Ten     { OneThread.Sleep ( -); A         return "Task finished"; -     }); -     //when a task is completed, it continues execution at the thread pool theTask. ContinueWith (t = -     { -Thread.Sleep ( -); - Console.WriteLine (Task. Result); +     }); -}

As you can see, the async and await keywords are not added in the Runasync method, but after the program is run, the main thread is not blocked. This is because ContinueWith will "hang" the delegate parameter into the thread pool's task queue, and the delegate will not begin execution until the task execution has ended. The ContinueWith method returns a task that is the task that will begin executing when the task executes, and the task can wait. Note that the difference between the continuewith and await keywords is that the await is executed by the main thread after the task is completed, but the methods in the ContinueWith continue to be executed by the threading pool.

Next, let's look at whether the task can be canceled and what happens when it is canceled.

C # provides a way to cancel a task that is "collaborative" and, when you construct a task, you first construct a System.Threading.CancellationTaskSource object that looks like this

1   Public Sealed classcancellationtasksource:idisposable{2      PublicCancellationTokenSource ();3      Public voidDispose ();//Freeing Resources4      Public BOOLiscancellationrequested{Get;}5      PublicCancellationToken token{Get;} 6      Public voidCancel ();//internal call cancel and pass false7      Public voidCancel (BOOLthrowonfirstexception);8}

The Cancellationtasksource object contains a token whose type is CancellationToken, which is a lightweight value type that contains a private reference to Cancellationtasksource. When you construct a task, you need to pass this token in, as shown below

1 Static voidMain (string[] args) {2 Canceltask ();3Console.WriteLine ("Async Run");4 Console.read ();5 }6  Public Static voidCanceltask () {7     //automatically cancel tasks after 1000ms timer8     varCancelsource =NewCancellationTokenSource ( +);9Task.run (() =    {Ten         //Simulate other tasks OneThread.Sleep (4000); AConsole.WriteLine ("Task over"); - }, Cancelsource.token); -CancelSource.Token.Register (() = Console.WriteLine ("Task Cancel")); the}

After running, you can see that the console shows the task cancel after about 1 seconds, and the task over is not displayed. The proof that the task was canceled. One of the overloads of the Task.run () method is to accept a canceltoken parameter, and we pass in the token of Cancelsource, which indicates that Cancelsource can control the cancellation of a task. My practice is to automatically cancel the task after 1 seconds, or you can manually call the Cancelsource.cancel () method to explicitly cancel the task. I subscribed to the canceled event on token, after the task was canceled, execute my method, here is the console print out the task cancel. You can also use "closures" in the task to pass tokens to the task, as follows

1 Static voidMain (string[] args) {2 Canceltask ();3Console.WriteLine ("Async Run");4 Console.read ();5 }6  Public Static voidCanceltask () {7     varCancelsource =NewCancellationTokenSource ( +);8Task.run (() ={9         intCount =0;Ten          for(inti =0; I < +; i++) One         { A             if(cancelsource.iscancellationrequested) -                  Break; -count+=i; theThread.Sleep ( -); -         } - Console.WriteLine (count); - }, Cancelsource.token); +CancelSource.Token.Register (() = Console.WriteLine ("Task Cancel")); -}

There are 2 methods for manual cancellation, one is Cancelsource.cancel () and the other is Cancelsource.cancelafter (), as shown below

1  Public Static voidCanceltask () {2     varCancelsource =NewCancellationTokenSource ();3Task.run (() =4     {5Thread.Sleep (4000);6Console.WriteLine ("Task over");7 }, Cancelsource.token);8CancelSource.Token.Register (() = Console.WriteLine ("Task Cancel"));9     //calling Cancelsource.cancel () here will end the task immediately.Ten     //This method cancels the task after about 1 seconds OneCancelsource.cancelafter ( +); A}

The example has the same effect as the delay of passing in 1000ms in the constructor above, and if Cancel () is called, the task is terminated immediately.

This is the content of this article, describes the Task.continuewith method, and how to cancel the task. If the text does not meet your requirements, you can view such as Task.run () or Task.continuewith () method of several overloads, there are other ways to use, I do not have all the details of learning, the main purpose is to master the basic use of multi-threading methods. The CLR via C # is also explained in detail in this series, which is extracted from the book and interested partners can take a look. Welcome to the problem and I am in the comment area to communicate.

Next, let me introduce you to C # parallel artifice: parallel for, foreach Loop, and PLINQ.

C # multithreaded programming (3)--turn on subtasks

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.