使用非阻塞任务

时间:2018-11-17 08:50:59

标签: c# multithreading winforms task

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

state('in', style({
        overflow: 'hidden',
        height: '*',
        width: '300px'
      })),

1 个答案:

答案 0 :(得分:1)

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;
        }