C # using Task asynchronous operation

  1. Why use Task
  2. Task and Thread difference
  3. Task Description
  4. Task is simple to achieve
  5. Task execution status

Why use Task

Threads are created and sent low-level tool, it has some limitations.

  • There is no easy way to get the thread "return value" from Union (Join). Therefore, you must create some shared domain. When an exception is thrown, the catch and handle exceptions also troublesome.
  • After the completion of the thread, the thread can not be started again. On the contrary, only joint (Join) it (in the process of blocking the current thread).

Task is a combination of - using the continuation connect them in series. They may be used to reduce the startup delay thread pool, and they can TaskCompletionSourceuse the callback method, to avoid a plurality of threads waiting for I / O intensive operations.

Task and Thread difference

1, the task is built on top of the thread, that task will eventually have to throw the thread to execute.

2, the task thread is not one to one relationship with such task is not to say the opening 10 will open 10 threads, this task is somewhat similar to the thread pool, but the task has little overhead and precise control compared to the thread pool.

Task and Thread as located System.Threading namespace

 

Compared with the thread, Taskis a higher level of abstraction, it identifies a concurrent operation with or without thread implementation.

Task Description

Task class represents a single operation does not return a value, typically performed asynchronously. Task object is a central idea of ​​task-based asynchronous mode was first introduced in the .NET Framework 4. Because usually executed on a thread pool thread rather than synchronously in the main application thread, you can use the Status property, and IsCanceled,, IsCompleted,, and IsFaulted property to determine the state of implementation of tasks by the Task objects asynchronously. In most cases, lambda expression is used to specify the task of the work performed.

Task is simple to achieve

To create a task by using the Task constructor, and call the Start method to start the task and perform asynchronous operations.

static  void Main ( String [] args) 
{ 
        Console.WriteLine ( " main thread to perform business process. " );
         // create a task 
        Task Task = new new Task (() => { 
            Console.WriteLine ( " Use System.Threading.Tasks .Task for asynchronous operation. " );
             for ( int I = 0 ; I < 10 ; I ++ ) 
            { 
                  Console.WriteLine (I); 
            } 
      }); 
     // start the task, and the task queue to arrange the current thread to perform the task 
       task .Start ();
      Console .WriteLine (" Perform other processing main thread " ); 
}

 

From the beginning Framework 4.5, start a background thread implemented by Task, can use the static method Task.Run

Task task = Task.Run(() =>
    {
        Thread.Sleep(2000);
        Console.WriteLine("Foo");
    });

 

 

Task use the thread pool by default, they are background threads. When the main thread means, stop all tasks will follow.

 

Task execution status

1. Wait (Wait)

Call Waitmethod can block tasks until the task is completed, the effect is equivalent to Thread.Join:

    Task task = Task.Run(() =>
    {
        Thread.Sleep(2000);
        Console.WriteLine("Foo");
    });
    Console.WriteLine(task.IsCompleted); //False
    task.Wait();//阻塞,直至任务完成
    Console.WriteLine(task.IsCompleted); //True
    Console.ReadLine();

2. Return Values

Task<TResult>It allows tasks to return a value. Calls Task.Run, passing a Func<TResult>proxy (or compatible Lambda expressions), instead of Action, you can get a Task <TResult>:

Task<int> task = Task.Run (() => { Console.WriteLine ("Foo"); return 3; });

int result = task.Result;      // Blocks if not already finished
Console.WriteLine (result);    // 3

 

The following example creates a task that uses LINQ to press before 3 million integers (2 starts) in the number of prime numbers:

Task<int> primeNumberTask = Task.Run(() =>
        Enumerable.Range(2, 3000000).Count(n => Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i => n % i > 0)));

    Console.WriteLine("Task running...");
    Console.WriteLine("The answer is " + primeNumberTask.Result);

This code will print "Task running ...", and then after a few seconds to print 216,815.

 

3. Task.Delay

Task.DelayIt is Thread.Sleepthe asynchronous version

Task.Delay(5000).GetAwaiter().OnCompleted(()=>Console.WriteLine(42));

or

Task.Delay(5000).ContinueWith(ant => Console.WriteLine(42));

 

 

References:

https://www.jianshu.com/p/4444f2d77f3b

https://www.cnblogs.com/pengstone/archive/2012/12/23/2830238.html

Guess you like

Origin www.cnblogs.com/ryanzheng/p/10963966.html