在C#中异步总是异步的吗? [英] Is async always asynchronous in C#?

查看:55
本文介绍了在C#中异步总是异步的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的项目在asyncawait上进行研发.我了解到的是,当调用async方法时,它将释放线程并让该线程供其他人使用.我们可以使用await关键字为可等待方法设置回调,并在结果准备好时该方法返回值.如果发生这种情况:

I am doing R&D on async and await for my project. What I have learned is that when async method is called, it frees the thread and let the thread to be used by others. We can set callback for await-able method using await keyword and that method returns value when the result is ready. If that happens:

  1. 我们应该能够在两次操作之间短暂访问UI.
  2. 执行时间应该比通常的同步方法调用要快.

就我而言,我对point 1毫无疑问,但是对于point 2来说,它的执行时间似乎与同步方法调用相同.例如,请参见Sample Code 1Sample Output 1

In my case, I have no question about point 1, But for point 2, it's execution time seems same as the synchronous method call. For example see Sample Code 1 and Sample Output 1

示例代码1:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Before Async Call");
            AsyncMethod();
            Console.WriteLine("After Async Call");

            Console.ReadLine();
        }

        public async static void AsyncMethod()
        {
            var firstValue = FirstAsyncMethod("FirstAsyncMethod has been called");
            Console.WriteLine("Middle of FirstAsyncMethod and SecondAsyncMethod");
            var secondValue = SecondAsyncMethod("SecondAsyncMethod has been called");
            Console.WriteLine(await firstValue);
            Console.WriteLine(await secondValue);
        }

        public static async Task<string> FirstAsyncMethod(string value)
        {
            for (int i = 0; i < 500000000; i++)
            {
                i = i + 1 - 1;
            }
            return "Success: "+value;
        }
        public static async Task<string> SecondAsyncMethod(string value)
        {
            for (int i = 0; i < 500000000; i++)
            {
                i = i + 1 - 1;
            }
            return "Success: " + value;
        }
    }

示例输出1:

Before Async Call
Middle of FirstAsyncMethod and SecondAsyncMethod
Success: FirstAsyncMethod has been called
Success: SecondAsyncMethod has been called
After Async Call

但是,如果我用Task.Run(()=> )调用async方法(例如Sample Code 2Sample Output 2),则与第一个示例(Sample Code 1)相比,它减少了执行时间.

But if I call the async method with Task.Run(()=> ) (For example Sample Code 2 and Sample Output 2), it reduces the execution time compared to first example (Sample Code 1).

示例代码2:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Before Async Call");
            AsyncMethod();
            Console.WriteLine("After Async Call");

            Console.ReadLine();
        }

        public async static void AsyncMethod()
        {
            var firstValue =Task.Run(()=> FirstAsyncMethod("FirstAsyncMethod has been called"));
            Console.WriteLine("Middle of FirstAsyncMethod and SecondAsyncMethod");
            var secondValue = Task.Run(() => SecondAsyncMethod("SecondAsyncMethod has been called"));
            Console.WriteLine(await firstValue);
            Console.WriteLine(await secondValue);
        }

        public static async Task<string> FirstAsyncMethod(string value)
        {
            for (int i = 0; i < 500000000; i++)
            {
                i = i + 1 - 1;
            }
            return "Success: "+value;
        }
        public static async Task<string> SecondAsyncMethod(string value)
        {
            for (int i = 0; i < 500000000; i++)
            {
                i = i + 1 - 1;
            }
            return "Success: " + value;
        }
    }

示例输出2:

Before Async Call
Middle of FirstAsyncMethod and SecondAsyncMethod
After Async Call
Success: FirstAsyncMethod has been called
Success: SecondAsyncMethod has been called

我的问题是,为什么第一个示例(Sample Code 1)像同步方法调用那样花时间?

My question is, why the first example (Sample Code 1) taking time like synchronous method call?

推荐答案

异步并不总是异步的. Visual Studio应该显示第一个方法不是异步的警告,因为没有任何等待的内容.

Async is not always asynchronous. Visual Studio should display a warning that the first method is not asynchronous because there is nothing to await.

此异步方法缺少等待"运算符,将同步运行. 考虑使用"await"运算符来等待非阻塞API调用, 或'await Task.Run(...)'在后台线程上进行CPU绑定的工作

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread

请注意,如今,异步无效的使用被认为是一种不好的做法.您应该始终将异步Taks用作异步方法的返回类型.

Note that the use of async void is considered a bad practice these days. You should always use async Taks for the return type of async methods.

有关详细信息,请参阅此文章

这篇关于在C#中异步总是异步的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆