Multithreading talk that some of the thing (task) ter cancel asynchronous and asynchronous methods multithreaded chat which of thing (task) ter cancel asynchronous and asynchronous methods

   hello, how are they to meet you, through the introduction of the previous two articles, the creation of the task of running, blocking, synchronization, continued operation and so have a good understanding and use of, the actual scene description, in this way the actual work can solve a large part of the business on multi-threaded, but only some of it is not enough, such as, for example, if such a scenario, when the open tsak asynchronous task, there is a trigger condition, needs execution termination tsak how should achieve it? This is exactly what some of the issues we need to share part of the exchange today, with some of these issues, we together into today's topic, thank you!

    Before entering the topic, if you have not read the previous two articles, please click on the address below to read about, so to be more consistent grasp the understanding of the contents of today, thank you!

  First: talk about what some of the one thing (task) to create multiple threads to run with obstruction

  Second: talk about multi-threaded which of thing (task) bis continuation of operation

  Part III: talk about multi-threaded which of thing (task) ter cancel asynchronous and asynchronous methods

 

Task of the mission canceled: CancellationTokenSource

 

    About thread cancellation, I believe we will encounter this problem in practice, no matter which way asynchronous thread, will have the appropriate mechanisms to cancel the thread operations. This will also dematerialization of Thread Thread, Tsak dematerialization threads simultaneously by examples.

    In my experience, it is necessary to cancel asynchronous thread operations actual usage scenarios often a number of asynchronous jobs program, which is the number of periodic cycles of business operations. Such as the regular data synchronization, data update operations and the like. For example: the electricity supplier system of a common scenario, orders canceled overtime and so on.

    In order to maintain consistency with the previous two examples, I am now or in the hotel business data synchronization platform as an example:

    Demand: Three 3 o'clock in the morning a week, provided by Ctrip hotel page query interface, the whole amount of synchronous data once the newest hotel. And data synchronization can be terminated through human intervention operation.

    Now I will be achieved through Thread and the task in two ways

    First, the task Thread era canceled

    Haha, tell the truth saying the project a few years ago, I also used to Thread asynchronous thread, the thread will encounter cancellation of business scenarios. I was implementation is to define a global variable, isStopThread time (whether to terminate the thread), been required to cancel the task, you only need to control isStopThread value, each execution of specific business, first determine what isStopThread, only the non-termination state before the implementation of specific business logic.

 /// <summary>
 /// Ctrip hotel data synchronization jobs (Thread)
 /// </summary>
 private static void CtripHoteDataSynchrByThread()
 {
     CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
     // The first step to open a thread by thread
     Thread thread = new Thread(() =>
     {
         // Get the number of data
         int getDataIndex = 1;
         isStopCtripHoteDataSynchr = false;
 // by calling the Ctrip paging service, the hotel gets its valid data // before getting data, first determine what the terminated acquisition
 the while (! cancellationTokenSource.IsCancellationRequested) {// Now suppose simulation, Ctrip get all valid data is available through the hotel three times finished Console.WriteLine ($ "Ctrip began to get the first page {getDataIndex} hotel data .... \ n " ); the Thread.Sleep (3000 ); Console.WriteLine ($" {getDataIndex} ctrip first property page data acquisition is complete \ n-" ); getDataIndex ++ ; // Get the third page-simulated data, the representative data acquisition is completed, terminate directly off IF (getDataIndex ==. 4 ) {Console.WriteLine ($ "the synchronized data hotels ctrip \ n" ); BREAK ;}} IF (isStopCtripHoteDataSynchr) {Console.WriteLine ($ "hotel ctrip canceled synchronization data \ n" );}}); thread.Start ( ); Console.WriteLine ( " data synchronization Ctrip hotel ..... \ n-" ); // simulate the actual data in synchronous cancel Console.WriteLine ( "to cancel data synchronization, then enter any of the characters to cancel \ n-" ); Console.ReadLine (); cancellationTokenSource.Cancel (); isStopCtripHoteDataSynchr to true =; Console.WriteLine ($ "Ctrip launched Cancel Sync hotel data request \ the n-" );}
 

Results of the:

    We can see the test results, on getting the first two data, then launched a canceled thread command. When the second page of data acquisition is completed, the thread terminates inside, so as to achieve the purpose of the thread cancellation.

    Second, the mission era Task canceled

    With the Task launch, Microsoft also launched a special service to help thread cancellation of classes (CancellationTokenSource), by type of good help we can cancel a thread, we did not talk much, we first realize the above example by CancellationTokenSource class Features.

/// <summary>
 /// Ctrip hotel data synchronization jobs (Task)
 /// </summary>
 private static void CtripHoteDataSynchrByTask()
 {
     // define tasks to cancel mechanism
     CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

     // The first step to open a thread by thread
     Task thread = new Task(() =>
     {
         // Get the number of data
         int getDataIndex = 1;
 // by calling the Ctrip paging service, the hotel gets its valid data // before getting data, first determine what the terminated acquisition

         while (!cancellationTokenSource.IsCancellationRequested)
         { // Now suppose simulation, get all valid data Ctrip's hotel by 3 times to get finished Console.WriteLine ($ "Ctrip began to get the first page {getDataIndex} hotel data .... \ the n-" ); Console.WriteLine ($ "Ctrip first page {getDataIndex} hotel data acquisition is completed \ the n-" ); getDataIndex ++ ; // After acquiring the analog data of the third page, the representative data acquisition is completed, terminate directly off IF (getDataIndex ==. 4 ) {Console.WriteLine ($ "the synchronized data hotels ctrip \ n-" ); BREAK ;}} IF (CancellationTokenSource. IsCancellationRequested) {Console.WriteLine ($ "hotel ctrip canceled synchronization data \ n-" );}}); Thread.Start (); Console.WriteLine ( "data synchronization Ctrip hotel ..... \ n-" ); / / simulation of the actual data synchronization cancel Console.WriteLine ( "If you need to cancel the data synchronization, then enter any character to operate \ n cancel" ); Console.ReadLine (); // cancel thread directly cancellationTokenSource.Cancel () ; // cancel thread after a specified time cancellationTokenSource.CancelAfter // (1000); Console.WriteLine ($ "Ctrip launched cancel sync hotel data \ n request" );}
 

Test Results:

 

    The test results, the results of two implementations of exactly the same

    Of course, CancellationTokenSource also provides CancelAfter (how long after cancellation) method to achieve canceled after long thread.

    Speaking of which, do not know if you have found a problem CancellationTokenSource its implementation is not no little to do with Task and Thread, Thread Thread achieved by the cancellation in the first instance, the same can be combined CancellationTokenSource to achieve. So, I said at the beginning of class to help CancellationTokenSource is a Microsoft provided a thread is canceled for this reason. In fact, I can open CancellationTokenSource realize source, in fact, we will be clear, the core logic cancel threads and above us say Thread cancellation principle is very similar, are controlled to achieve the value of a variable, but CancellationTokenSource conduct all of its operations a package. Which CancelAfter which is to open a definition, a timer or ultimately Canel and the same. If you want to see CancellationTokenSource source code, you can view the following address: https: //www.cnblogs.com/majiang/p/7920102.html

Finally, it should be noted that the Task and CancellationTokenSource are .net Framework4.0 + ,. NET Core, .NET Standard.

 

The asynchronous method: (async / await)

 

    c # 5.0, Microsoft introduced a new feature that is asynchronous method keyword is async. With async we want to achieve an asynchronous method will simply much more attractive, you will find and implement a synchronization method is very similar, only it needs to be modified to async method. Of course, if simply decorated call, then the call will also be synchronous, asynchronous calls in order to achieve a real, often need to await another keyword to use with.

    Briefly explain async asynchronous function:

    async return three types:

    Tsak: The main scenario is applied, the main program concerned only with the asynchronous method execution state, and the main thread does not need to have any of the results of data exchange.

    Task <T>: The main scenario is applicable, not only the main concern asynchronous method execution state, and also want to return after performing a data type of the result T

    void: the main program neither relationship asynchronous method execution status, do not care about the results of its execution, but the main program calls an asynchronous method, in addition to the code for the event handler, usually do not encourage the use of async void method, because the caller is not

    In the introduction await Keywords:

    await its name suggests is waiting for the meaning, its operating principle is: the caller's execution will return immediately to await, but wait for asynchronous asynchronous method execution results. So await only exist in async modified asynchronous method body, await not block the main thread, just blocking the current asynchronous method continues down, so that you can achieve true asynchronous.

Below a simple example to illustrate the use of each case:

static void Main(string[] args)
 {
     Console.WriteLine ( "main thread begins \ the n-" );
     Console.WriteLine ( "main thread calls a synchronization method: SynTest \ the n-" );
     Had appeared ();

     Console.WriteLine ( "main thread asynchronous method call: AsyncTestNoAwait \ the n-" );
     AsyncTestNoAwait();
 Console.WriteLine ( "main thread asynchronous method call: AsyncTestHasAwait \ the n-" );
     AsyncTestHasAwait();
 Console.WriteLine ( "main thread end \ n-" ); the Console.ReadKey ();} /// <Summary> /// synchronization test method /// </ Summary> public static void SynTest () {Console.WriteLine ( "synchronization method SynTest runs \ n-" ); the Thread.Sleep (5000 ); Console.WriteLine ( "end synchronization method SynTest run \ n-" );} /// <Summary> /// asynchronous test method (without await keyword) /// </ Summary> public static void the async AsyncTestNoAwait () {Console.WriteLine ( "asynchronous method AsyncTestNoAwait runs \ n-" ); the Thread.Sleep (5000 ); Console.WriteLine ( "running asynchronous method AsyncTestNoAwait end \ n-" );} /// <Summary> /// asynchronous test method (with await keyword) /// </ Summary> public static void the async AsyncTestHasAwait () {Console.WriteLine (" asynchronous method begins AsyncTestHasAwait run \ the n-" ); the await Task.Delay (5000 ); Console.WriteLine ( "End Run asynchronous method AsyncTestHasAwait \ n-" );}

operation result:

From the results we can run a good draw:

    1, if not await an asynchronous method async keyword, its implementation principles or synchronous call

    2, await cloud async keyword can only exist modified method body

    3, in the asynchronous method call async, only encountered block is executed asynchronously after the await keyword, its pre await keyword or synchronous code block execution

    Well, management async first introduced here, because of the time and article space reasons, not in detail, there is also a lot of things you need to do a follow-up in real async / await the feature article.

to sum up:

    So far, three articles on Task are to this end, the following points summarize the relevant functions in the Task bar review!

    1. Create a Task can run in three ways: new Task / Task.Factory / Task.Run

    2, Task returns a parameter definition Task <return type>

        Get Return Value: Task.Result-> to block the main flow

    3, synchronous implementation Task threads can only be achieved through synchronous operation RunSynchronously, of course, can also be changed to achieve through Task.Result / Task.Wait etc.

    4, Task of wait / waitAll / waitAny blocked waiting for the results achieved

    5, Task of WhenAny, WhenAll, ContinueWith achieve continued operation

    6, CancellationTokenSource asynchronous tasks canceled

    7, the asynchronous method: (async / await) achieve synchronous and asynchronous calls, etc.

 

I guess you'll like: 

 First: talk about what some of the one thing (task) to create multiple threads to run with obstruction

 Second: talk about multi-threaded which of thing (task) bis continuation of operation

END
For more exchanges, we welcome public attention to my number, scan the following QR code to follow, thanks:

Guess you like

Origin www.cnblogs.com/xiaoXuZhi/p/XYH_tsak_WhenAny1.html