C# 语言中的 Async 和 Await

C# 的 Async 和 await 关键字是在 C# 5.0 中引入的。它们旨在简化异步代码的编写过程,这些代码可以在执行其他代码时在后台运行。

“async” 关键字将方法标记为异步,这意味着它可以在后台运行,同时执行另一个代码。将方法标记为异步时,可以使用 “await” 关键字来指示该方法应等待异步操作的结果,然后再继续。

在 C 中使用 'async' 和 'await'#

异步编程是一种编程技术,它允许并发执行代码而不会阻止调用线程的执行。换句话说,异步代码可以在执行其他代码时在后台运行。在同步编程中,每一行代码都是按顺序执行的,程序会等待每个操作完成,然后再进行下一个操作。这可能会导致性能问题,尤其是在需要执行长时间运行的操作(如 I/O 或网络请求)的程序中。

异步编程允许程序在不阻塞调用线程的情况下执行这些操作。当异步操作启动时,程序在等待操作完成时继续执行其他代码。操作完成后,程序会收到通知,并且可以继续执行以下代码行。

异步编程可以使用各种技术实现,例如回调、事件和 Promise。在 C# 中,“async”和“await”关键字提供了一种编写异步代码的便捷方法,该代码看起来类似于同步代码,使其更易于阅读和维护。

在 async 和 await 关键字的帮助下,我们将以更少的努力获得传统异步编程的所有好处。

假设我们使用两种方法,分别是 Method1 和 Method2,并且两种方法彼此不依赖,并且 Method1 需要很长时间才能完成任务。在 Synchronous programming 中,会执行第一个 Method1,等待这个 Method 完成,然后执行 Method2。因此,即使这两种方法并不相互依赖,这也将是一个耗时的过程。

我们可以使用简单的线程编程并行运行所有方法,但它会阻塞 UI 并等待完成所有任务。为了解决这个问题,我们必须在传统编程中编写太多的代码,但是如果我们使用 async 和 await 关键字,我们将用更少的代码获得解决方案。

此外,我们将看到更多示例,如果任何第三个 Method,因为 Method3 依赖于 method1,它将在 await 关键字的帮助下等待 Method1 完成。

C# 中的 Async 和 await 是代码标记,用于标记代码位置,控件在完成任务后应从中恢复。

让我们从理解编程概念的实际示例开始。

C# async await 的代码示例

我们将使用一个控制台应用程序进行演示。

示例 1

在此示例中,我们将采用两种彼此不依赖的方法。

class Program
{
    static void Main(string[] args)
    {
        Method1();
        Method2();
        Console.ReadKey();
    }

    public static async Task Method1()
    {
        await Task.Run(() =>
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(" Method 1");
                // Do something
                Task.Delay(100).Wait();
            }
        });
    }


    public static void Method2()
    {
        for (int i = 0; i < 25; i++)
        {
            Console.WriteLine(" Method 2");
            // Do something
           Task.Delay(100).Wait();
        }
    }
}

在上面的代码中,Method1 和 Method2 彼此不依赖,我们从 Main 方法调用。

在这里,我们可以看到 Method1 和 Method2 并没有相互等待。

输出

关于第二个示例,假设我们有 Method3,它依赖于 Method1。

在此示例中,Method1 以整数值的形式返回总长度,我们在 Method3 中将参数作为长度传递,该长度来自 Method1。

在这里,我们必须在 Method3 中传递参数之前使用 await 关键字,为此,我们必须使用调用方法中的 async 关键字。

我们将创建一个名为 callMethod 的新方法,在此方法中,我们将分别调用所有方法 Method1、Method2 和 Method3。

代码示例 C# 

class Program
{
    static void Main(string[] args)
    {
        callMethod();
        Console.ReadKey();
    }

    public static async void callMethod()
    {
        Task<int> task = Method1();
        Method2();
        int count = await task;
        Method3(count);
    }

    public static async Task<int> Method1()
    {
        int count = 0;
        await Task.Run(() =>
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(" Method 1");
                count += 1;
            }
        });
        return count;
    }

    public static void Method2()
    {
        for (int i = 0; i < 25; i++)
        {
            Console.WriteLine(" Method 2");
        }
    }

    public static void Method3(int count)
    {
        Console.WriteLine("Total count is " + count);
    }
}

代码示例 C# 

class Program
 {
   static async Task Main(string[] args)
   {
     await callMethod();
     Console.ReadKey();
   }

   public static async Task callMethod()
   {
     Method2();
     var count = await Method1();
     Method3(count);
   }

   public static async Task<int> Method1()
   {
     int count = 0;
     await Task.Run(() =>
     {
       for (int i = 0; i < 100; i++)
       {
         Console.WriteLine(" Method 1");
         count += 1;
       }
     });
     return count;
   }

   public static void Method2()
   {
     for (int i = 0; i < 25; i++)
     {
       Console.WriteLine(" Method 2");
     }
   }

   public static void Method3(int count)
   {
     Console.WriteLine("Total count is " + count);
   }
}

在上面的代码中,Method3 需要一个参数,即 Method1 的返回类型。在这里,await 关键字对于等待 Method1 任务完成至关重要。

输出

实时示例

某些运行时支持 .NET Framework 4.5 中的 API,而 Windows 运行时包含支持异步编程的方法。

我们可以在 async 和 await 关键字的帮助下在实时项目中使用所有这些,以更快地执行任务。

一些包含异步方法的 API 包括 HttpClient、SyndicationClient、StorageFile、StreamWriter、StreamReader、XmlReader、MediaCapture、BitmapEncoder、BitmapDecoder 等。

在此示例中,我们将异步读取大型文本文件中的所有字符,并获取所有字符的总长度。

示例代码

class Program
{  
    static void Main()
    {
        Task task = new Task(CallMethod);
        task.Start();
        task.Wait();
        Console.ReadLine();
    }

    static async void CallMethod()
    {
        string filePath = "E:\\sampleFile.txt";
        Task<int> task = ReadFile(filePath);

        Console.WriteLine(" Other Work 1");
        Console.WriteLine(" Other Work 2");
        Console.WriteLine(" Other Work 3");

        int length = await task;
        Console.WriteLine(" Total length: " + length);

        Console.WriteLine(" After work 1");
        Console.WriteLine(" After work 2");
    }

    static async Task<int> ReadFile(string file)
    {
        int length = 0;

        Console.WriteLine(" File reading is stating");
        using (StreamReader reader = new StreamReader(file))
        {
            // Reads all characters from the current position to the end of the stream asynchronously
            // and returns them as one string.
            string s = await reader.ReadToEndAsync();

            length = s.Length;
        }
        Console.WriteLine(" File reading is completed");
        return length;
    }
}

在上面给出的代码中,我们调用 ReadFile 方法来读取文本文件的内容并获取文本文件中存在的总字符的长度。

输出

在这里,我们必须了解要点:如果我们不使用 await 关键字,那么该方法会同步工作。因此,编译器将向我们显示警告,但不会显示任何错误。

我们可以在 C# 中使用 async 和 await 关键字以这种简单的方式实现异步编程,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暗夜独舞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值