繁体   English   中英

使用非阻塞任务

[英]Using non-blocking tasks

以下代码返回了不正确的产品。 我希望我需要在AsyncMultiply函数中使用await术语,并尝试将其添加到所有行的前面,但这没有用。 我该如何修复代码,以使任务成为非阻塞的,正确计算的任务?

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

namespace NonBlockingTasks
{
    class Program
    {
        static int prod;
        public static void Main(string[] args)
        {
            Task.Run(async () => { await AsyncMultiply(2, 3); });

            for(int i = 0; i < 10; i++) {
                Console.Write(i + " ");
                Thread.Sleep(100);
            }

            Console.WriteLine();
            Console.WriteLine("Prod = " + prod);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey();
        }

        public static async Task DoSomethingAsync()
        {
          await Task.Delay(100);
        }           

        public static async Task<int> AsyncMultiply(int a, int b)
        {
            Thread.Sleep(2000);
            prod = a * b;
            return prod;
        }
    }
}

Task.Run返回一个Task,而您不必等待它完成。 如果您使用的是C#7.1(.net 4.7)或更高版本,则可以将等待的方式一直显示到调用者:

        static int prod;
        public static async Task Main(string[] args)
        {
            Task running  = Task.Run(async () => { await AsyncMultiply(2, 3); });

            for (int i = 0; i < 10; i++)
            {
                Console.Write(i + " ");
                Thread.Sleep(100);
            }

            await running; // Wait for the previously abandoned task to run.


            Console.WriteLine();
            Console.WriteLine("Prod = " + prod);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey();
        }

        public static async Task DoSomethingAsync()
        {
            await Task.Delay(100);
        }

        public static async Task<int> AsyncMultiply(int a, int b)
        {
            Thread.Sleep(2000);
            prod = a * b;
            return prod;
        }

否则,您可以冻结当前线程,等待任务完成:

        static int prod;
        public static void Main(string[] args)
        {
            Task running  = Task.Run(async () => { await AsyncMultiply(2, 3); });

            for (int i = 0; i < 10; i++)
            {
                Console.Write(i + " ");
                Thread.Sleep(100);
            }

            running.Wait(); // Freeze thread and wait for task.


            Console.WriteLine();
            Console.WriteLine("Prod = " + prod);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey();
        }

        public static async Task DoSomethingAsync()
        {
            await Task.Delay(100);
        }

        public static async Task<int> AsyncMultiply(int a, int b)
        {
            Thread.Sleep(2000);
            prod = a * b;
            return prod;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM