首页 > 解决方案 > 使用非阻塞任务

问题描述

以下代码返回不正确的产品。我希望我需要在我的 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;
        }
    }
}

标签: c#multithreadingwinformstask

解决方案


Task.Run 返回一个任务,您无需等待它完成。如果您使用的是 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;
        }

推荐阅读