. Net 4.0 Parallel programming (6) Task (bottom)

Source: Internet
Author: User

In previous articles, we have introduced the basic usage of tasks and how to cancel tasks and continue tasks. This Post mainly introduces the Task Exception Handling and Wait functions, and provides the Wait time for execution.

In TPL, we can wait in three ways. One is to wait through the WaitHanle of CancellTaken, and the other is to use the traditional Tread. the Sleep method and the third method use Thread. spainWait method.

CancellToken method:

static void Main(string[] args){    var cancell = new CancellationTokenSource();    var token = cancell.Token;    var task = new Task(() =>    {        for (var i = 0; i < 100000; i++)        {            var cancelled = token.WaitHandle.WaitOne(10000);            Console.WriteLine(" {0}. Cancelled? {1}",                        i, cancelled);            if (cancelled)            {                throw new OperationCanceledException(token);            }        }    }, token);    task.Start();    Console.WriteLine("Press enter to cancel token.");    Console.ReadLine();    cancell.Cancel();    Console.WriteLine("Main method complete. Press enter to finish.");    Console.ReadLine();}

Every time we wait for 10 seconds, we will output it again.

If the above functions are implemented through Tread. Sleep:

var task = new Task(() =>{    for (var i = 0; i < 100000; i++)    {        Thread.Sleep(10000);        var cancelled = token.IsCancellationRequested;        Console.WriteLine(" {0}. Cancelled? {1}",                    i, cancelled);        if (cancelled)        {            throw new OperationCanceledException(token);        }    }}, token);

Thread. SpainWait is completely different from the above methods. The above two methods will not consider modifying the Thread in the Thread scheduler and wait until the running ends. The role of Thread. SpainWait will put the processor in a very tight loop, and the main role is to implement the Synchronous lock. It is not commonly used. In most cases, we can use the Lock method.

Waiting for task execution

In many cases, we may need to wait for several threads to be enabled at the same time before doing other things. In TPL, we provide several methods to wait for the task to be executed. Task. Wait waits for the completion of a single Task; Task. WaitAll waits for the completion of all tasks, TaskAny, and so on.

Task. Wait:

Task. Wait has five reloads: Wait (), Wait (CancellToken), Wait (Int32), Wait (TimeSpan), and Wait (TimeSpan, CancellToken ). Meanings of each overload method:

1) Wait (): Wait until the entire task is completed or cancel or an exception occurs;

2) Wait (CancellToken): Wait until the CancellToken call is canceled, or an exception occurs;

3) Wait (Int32): Wait for the task. The specified time is reached when the task is not completed;

4) Wait (TimeSpan): Same as above;

5) Wait (TimeSpan, CancellToken): Wait for the task to reach the specified time, or cancel the CancellToken call or complete the task.

Example:

static void Main(string[] args){    var tokenSource = new CancellationTokenSource();    CancellationToken token = tokenSource.Token;    Task task = createTask(token,6);    task.Start();    Console.WriteLine("Wait() complete.");    task.Wait();    Console.WriteLine("Task Completed.");    task = createTask(token,3);    task.Start();    Console.WriteLine("Wait(2) secs for task to complete.");    bool completed = task.Wait(2000);    Console.WriteLine("Wait ended - task completed: {0}", completed);    task = createTask(token,4);    task.Start();    Console.WriteLine("Wait(2,token) for task to complete.");    completed = task.Wait(2000, token);    Console.WriteLine("Wait ended - task completed: {0} task cancelled {1}",    completed, task.IsCanceled);    Console.WriteLine("Main method complete. Press enter to finish.");    Console.ReadLine();}static Task createTask(CancellationToken token,int loop){    return new Task(() =>    {        for (int i = 0; i < loop; i++)        {            token.ThrowIfCancellationRequested();            Console.WriteLine("Task - Int value {0}", i);            token.WaitHandle.WaitOne(1000);        }    }, token);}

The loop will Wait for 1 second, so we can see the effect of Wait (2000) and the effect after running:

Task. WaitAll

The WaitAll method is to wait for all the tasks to be completed and there are also five reloads. Let's take a look at the example:

static void Main(string[] args){    var tokenSource = new CancellationTokenSource();    CancellationToken token = tokenSource.Token;    var task1 = createTask(token,2);    var task2 = createTask(token, 5);    task1.Start();    task2.Start();    Console.WriteLine("Waiting for tasks to complete.");    Task.WaitAll(task1, task2);    Console.WriteLine(
Related Article

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.