Asynchronous Programming (3)

How to handle asynchronous tasks in batches? We have a function called WaitAll, which is used for batch asynchronous task waiting. WhenAny is used for task completion

Asynchronous tasks wait. All tasks are complete

Task. WaitAll (array);Copy the code

Asynchronous task completion operation, one task complete

Task. WhenAny (array);Copy the code
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace StudyRecordProject
{
    class Program
    {
        static async Task Main(string[] args)
        {

            List<Task> tasks = new List<Task>();
            // Loop 10 times, statistics 1 class
            Console.WriteLine("Start loop statistics Category 1");
            for (int i = 0; i < 10; i++)
            {
                tasks.Add(Task.Factory.StartNew(() => Statistics01(), TaskCreationOptions.LongRunning));
            }// Statistics class 2
            Console.WriteLine("Start counting category 2.");
            tasks.Add(Task.Run(Statistics02));
            // Class 3
            Console.WriteLine("Start counting in category 3.");
            tasks.Add(Task.Run(Statistics03));

            Task.WaitAll(tasks.ToArray());
            //Console.WriteLine(we);
            Console.WriteLine("Close count");
        }

        /// <summary>
        ///Statistical 1
        /// </summary>
        /// <returns></returns>
        static int Statistics01()
        {
            // Wait 20 seconds
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(i);
                Thread.Sleep(1000);
            }
            Console.WriteLine("I'm in statistics 1, 10 seconds.");
            return 10;
        }

        /// <summary>
        ///Statistical 2
        /// </summary>
        /// <returns></returns>
        static int Statistics02()
        {
            for (int i = 0; i < 20; i++)
            {
                Thread.Sleep(1000);
            }
            Console.WriteLine("I'm in stats 2, 20 seconds.");
            return 20;
        }

        /// <summary>
        ///Statistics 3
        /// </summary>
        /// <returns></returns>
        static int Statistics03()
        {
            for (int i = 0; i < 30; i++)
            {
                Thread.Sleep(1000);
            }
            Console.WriteLine("I'm in stats 3, 30 seconds.");
            return 30; }}}Copy the code

Welcome to qq group communication: 704028989