Asynchronous Programming (2)

The method used in the previous chapter used task.delay (1); The Delay is asynchronous. If we do not need Delay and only use asynchrony, we can directly use task.run with method name as parameter to asynchrony. The core code

Task.run (method name);Copy the code

You can also use Lambda, where you can receive the return value as an argument.

Task. Factory. StartNew (() = > method name (), TaskCreationOptions. LongRunning);Copy the code

The complete code

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

namespace StudyRecordProject
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Statistics class 1
            Console.WriteLine("Start counting category 1");
            var num1 = Task.Factory.StartNew(() => Statistics01(), TaskCreationOptions.LongRunning);
            // Statistics class 2
            Console.WriteLine("Start counting category 2.");
            var num2 = Task.Run(Statistics02);
            // Class 3
            Console.WriteLine("Start counting in category 3.");
            var num3 = Task.Run(Statistics03);
            var we = await num1 + await num2 + await num3;
            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