Multitasking of Task C #

Task is the What?

Task is a class that represents an operation does not return a value, typically performed asynchronously. 

Task object is a central idea  -based Asynchronous Pattern mission  was first introduced in the .NET Framework 4.

System.Object
  System.Threading.Tasks.Task
    System.Threading.Tasks.Task<TResult>

Because the implementation  is usually performed on a thread pool thread rather than synchronously in the main application thread, you can use the Task objects asynchronously  Status  property, and  IsCanceled ,, the IsCompleted ,, and  IsFaulted  property to determine the status of the task.  In most cases, lambda expression is used to specify the task of the work performed.

 

Task how to use?

Task variety of ways to create an instance.  The most commonly used method, which is located at the beginning of .NET Framework 4.5,, is to call the static  Run  method. Run  method provides a simple way to start the task using the default value, and requires no additional parameters.  The following example uses  Run (Action)  method to start the cycle, and then displays the number of loop iterations task ︰ 

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Run( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
      t.Wait();
   }
}


using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task t = Task.Factory.StartNew( () => {
                                  // Just loop.
                                  int ctr = 0;
                                  for (ctr = 0; ctr <= 1000000; ctr++)
                                  {}
                                  Console.WriteLine("Finished {0} loop iterations",
                                                    ctr);
                               } );
      t.Wait();
   }
}

Because the tasks typically run asynchronously on a thread pool thread, create and start a thread will continue to execute the task, once the task is instantiated.  In some cases, actually begins to execute any task before the calling thread when the main application thread, the application may be terminated.  In other cases, the logic of the application may require the calling thread to continue only if one or more tasks executed.  You can synchronize the calling thread of execution, as well as asynchronous tasks it starts by calling the  Wait  method to wait to complete one or more tasks.

To wait for the completion of a task, you can call it  Task.Wait  method.  Call  Wait  method blocks the calling thread until a single instance of the class have completed execution.

Calling an example below  the Wait ()  method, unconditionally to wait until the task is completed.  The simulation work task by calling  Thread.Sleep  method goes to sleep for two seconds.

using System;   
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static Random rand = new Random();

    static void Main()
    {
        // Wait on a single task with no timeout specified.
        Task taskA = Task.Run( () => Thread.Sleep(2000));
        Console.WriteLine("taskA Status: {0}", taskA.Status);
        try {
          taskA.Wait();
          Console.WriteLine("taskA Status: {0}", taskA.Status);
       } 
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
    }    
}


You can conditionally wait for task completion. Wait (Int32)  and  Wait (TimeSpan)  method blocks the calling thread until the task is completed or the end of the timeout interval, depending on the first one.  As the following example will start a task that sleep two seconds, but the definition of one second timeout, the calling thread is blocked until the timeout expired and before the task has completed execution. 

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Wait on a single task with a timeout specified.
      Task taskA = Task.Run( () => Thread.Sleep(2000));
      try {
        taskA.Wait(1000);       // Wait for 1 second.
        bool completed = taskA.IsCompleted;
        Console.WriteLine("Task A completed: {0}, Status: {1}",
                         completed, taskA.Status);
        if (! completed)
           Console.WriteLine("Timed out before task A completed.");                 
       }
       catch (AggregateException) {
          Console.WriteLine("Exception in taskA.");
       }   
   }
}


You can also provide a cancellation token by calling the  Wait (CancellationToken)  and  Wait (Int32, CancellationToken)  method.  If the token  IsCancellationRequested  attribute  to true ,, wait cancellation; if it goes to true  the Wait  method terminates.

Execution of tasks, in some cases, you may want to wait for the completion of the first series, but it is not the task of attention.  For this purpose, you can call one of the overloads of  Task.WaitAll  method.  The following example creates three tasks, wherein each dormant random number generator determines time intervals. WaitAny (Task [])  method waits for the first task is completed.  This example then displays information about the status of all three tasks. 

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new Task[3];
      var rnd = new Random();
      for (int ctr = 0; ctr <= 2; ctr++)
         tasks[ctr] = Task.Run( () => Thread.Sleep(rnd.Next(500, 3000)));

      try {s
         int index = Task.WaitAny(tasks);
         Console.WriteLine("Task #{0} completed first.\n", tasks[index].Id);
         Console.WriteLine("Status of all tasks:");
         foreach (var t in tasks)
            Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
      }
      catch (AggregateException) {
         Console.WriteLine("An exception occurred.");
      }
   }
}

You can also wait for the call to complete a series of tasks all  WaitAll  method.  The following example creates 10 tasks, waiting for all ten to complete, and then display its status.

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Wait for all tasks to complete.
      Task[] tasks = new Task[10];
      for (int i = 0; i < 10; i++)
      {
          tasks[i] = Task.Run(() => Thread.Sleep(2000));
      }
      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
         Console.WriteLine("One or more exceptions occurred: ");
         foreach (var ex in ae.Flatten().InnerExceptions)
            Console.WriteLine("   {0}", ex.Message);
      }   

      Console.WriteLine("Status of completed tasks:");
      foreach (var t in tasks)
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
   }
}

Please note that any abnormal spread on the thread while waiting for the call to complete one or more tasks, then running task triggered  Wait  method, as shown in the following example.  It will start normally completed three of 12 three tasks and what was thrown.  The remaining six tasks, three before the start date, will be canceled, while three will be executed when they are canceled.  Exception is thrown  WaitAll  method call, and the processing is  the try / the catch  block.

using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      // Create a cancellation token and cancel it.
      var source1 = new CancellationTokenSource();
      var token1 = source1.Token;
      source1.Cancel();
      // Create a cancellation token for later cancellation.
      var source2 = new CancellationTokenSource();
      var token2 = source2.Token;

      // Create a series of tasks that will complete, be cancelled, 
      // timeout, or throw an exception.
      Task[] tasks = new Task[12];
      for (int i = 0; i < 12; i++)
      {
          switch (i % 4) 
          {
             // Task should run to completion.
             case 0:
                tasks[i] = Task.Run(() => Thread.Sleep(2000));
                break;
             // Task should be set to canceled state.
             case 1:   
                tasks[i] = Task.Run( () => Thread.Sleep(2000),
                         token1);
                break;         
             case 2:
                // Task should throw an exception.
                tasks[i] = Task.Run( () => { throw new NotSupportedException(); } );
                break;
             case 3:
                // Task should examine cancellation token.
                tasks[i] = Task.Run( () => { Thread.Sleep(2000); 
                                             if (token2.IsCancellationRequested)
                                                token2.ThrowIfCancellationRequested();
                                             Thread.Sleep(500); }, token2);   
                break;
          }
      }
      Thread.Sleep(250);
      source2.Cancel();

      try {
         Task.WaitAll(tasks);
      }
      catch (AggregateException ae) {
          Console.WriteLine("One or more exceptions occurred:");
          foreach (var ex in ae.InnerExceptions)
             Console.WriteLine("   {0}: {1}", ex.GetType().Name, ex.Message);
       }   

      Console.WriteLine("\nStatus of tasks:");
      foreach (var t in tasks) {
         Console.WriteLine("   Task #{0}: {1}", t.Id, t.Status);
         if (t.Exception != null) {
            foreach (var ex in t.Exception.InnerExceptions)
               Console.WriteLine("      {0}: {1}", ex.GetType().Name,
                                 ex.Message);
         }
      }
   }
}

Four: Parallel Iterative Task.Parallel


The API determines how many threads at the same time the most efficient execution. Efficiency is determined by a hill-climbing algorithm.

Examples of a parallel parallel

Guess you like

Origin www.cnblogs.com/wwwbdabc/p/11652079.html