不要错过 .NET 中关于异步/等待任务的前 5 个示例

作者:微信公众号:【架构师老卢】
2-14 19:14
95

你听说过“经验丰富的”开发人员这个词吗?

这是一个在他身上有盐和胡椒的开发商。

好的 好的。对不起,我再也忍不住了。我知道,我很有趣。

顺便说一句,既然我已经开起了我的笑话,那就是过去两天的烹饪,是时候专注于下一个高级软件面试问题了。

我们将探讨的问题是:

Async/Await takes 如何在 .NET 中工作?

我还整理了几个例子来帮助你更好地理解这些想法。

如果您想在 Medium 中获得更多最佳笑话,请邀请您从我的个人资料订阅我的时事通讯。您将收到我下一篇文章的电子邮件通知。

现在,将您的战利品放在一个舒适的位置,让我们开始吧!

介绍

Async/Await 是编程中的一项强大功能,可简化异步编程,使其更具可读性和可维护性。

如今,它几乎可以在任何地方找到。从python,unity,C++,JS到C#/.NET。

在处理可能需要时间才能完成的任务(如 I/O 操作或网络请求)时,它特别有用。

在本文中,我们将深入探讨 .NET 中 Async/Await 任务的基础知识,并提供 C# 中的五个实际示例。

了解异步/等待

Async 和 Await 是协同工作以在 C# 中创建异步代码的关键字。

修饰符在方法签名中用于指示方法包含异步操作,并用于指示异步操作发生的位置。asyncawait

当异步方法遇到关键字时,它会将当前线程释放回调用代码,从而允许它执行其他任务。等待的操作完成后,该方法将从中断的位置恢复执行。await

让我们看一下这些例子。

示例 1️⃣ 简单的 async/await 任务

using System;  
using System.Threading.Tasks;  
  
class Program  
{  
    static async Task Main()  
    {  
        await PrintMessageAsync();  
    }  
  
    static async Task PrintMessageAsync()  
    {  
        Console.WriteLine("Start of async method.");  
        await Task.Delay(2000); // Simulating an asynchronous delay  
        Console.WriteLine("End of async method.");  
    }  
}

在此示例中,我们有一个简单的异步方法,该方法在模拟延迟 2000 毫秒后使用 打印消息。该方法也被标记为 并等待 的完成。PrintMessageAsyncTask.DelayMainasyncPrintMessageAsync

  • async Task PrintMessageAsync():在延迟后打印消息的异步方法。
  • await Task.Delay(2000):模拟 2000 毫秒的异步延迟。
  • await PrintMessageAsync():方法异步等待完成。MainPrintMessageAsync

示例 2️⃣ 使用 Task.Run 的 Async/Await

using System;  
using System.Threading.Tasks;  
  
class Program  
{  
    static async Task Main()  
    {  
        await PerformTaskAsync();  
    }  
  
    static async Task PerformTaskAsync()  
    {  
        Console.WriteLine("Start of async method.");  
  
        // Using Task.Run to run a synchronous method asynchronously  
        await Task.Run(() => PerformSynchronousTask());  
  
        Console.WriteLine("End of async method.");  
    }  
  
    static void PerformSynchronousTask()  
    {  
        Console.WriteLine("Executing synchronous task.");  
    }  
}

此示例演示如何使用 异步运行同步方法。该方法使用 .Task.RunPerformTaskAsyncPerformSynchronousTaskTask.Run

  • await Task.Run(() => PerformSynchronousTask()):使用 异步执行。PerformSynchronousTaskTask.Run
  • PerformSynchronousTask():异步执行的同步方法。

示例 3️⃣ 具有异常处理的 Async/Await

using System;  
using System.Threading.Tasks;  
  
class Program  
{  
    static async Task Main()  
    {  
        try  
        {  
            await PerformAsyncOperationWithErrorAsync();  
        }  
        catch (Exception ex)  
        {  
            Console.WriteLine($"Exception caught: {ex.Message}");  
        }  
    }  
  
    static async Task PerformAsyncOperationWithErrorAsync()  
    {  
        Console.WriteLine("Start of async method with exception.");  
  
        // Simulating an asynchronous operation that throws an exception  
        await Task.Run(() => throw new InvalidOperationException("Async operation failed."));  
  
        Console.WriteLine("End of async method with exception.");  
    }  
}

在此示例中,我们将引入异步代码中的异常处理。该方法抛出一个 .该方法捕获异常。PerformAsyncOperationWithErrorAsyncInvalidOperationExceptionMain

  • await Task.Run(() => throw new InvalidOperationException()):模拟引发异常的异步操作。
  • catch (Exception ex):捕获并处理异步操作引发的异常。

示例 4️⃣ 具有多个任务的异步/等待

using System;  
using System.Threading.Tasks;  
  
class Program  
{  
    static async Task Main()  
    {  
        await Task.WhenAll(DownloadDataAsync(), ProcessDataAsync());  
    }  
  
    static async Task DownloadDataAsync()  
    {  
        Console.WriteLine("Downloading data asynchronously.");  
        await Task.Delay(3000); // Simulating download operation  
        Console.WriteLine("Download complete.");  
    }  
  
    static async Task ProcessDataAsync()  
    {  
        Console.WriteLine("Processing data asynchronously.");  
        await Task.Delay(2000); // Simulating data processing  
        Console.WriteLine("Data processing complete.");  
    }  
}

此示例演示了如何使用 以等待并发完成多个异步任务。该方法等待两者并完成。Task.WhenAllMainDownloadDataAsyncProcessDataAsync

  • await Task.WhenAll(DownloadDataAsync(), ProcessDataAsync()):等待两个任务完成。
  • DownloadDataAsync()和 :模拟并发运行的异步操作(下载和数据处理)。ProcessDataAsync()

示例 5️⃣ 使用 CancellationToken 的 Async/Await

using System;  
using System.Threading;  
using System.Threading.Tasks;  
  
class Program  
{  
    static async Task Main()  
    {  
        using (var cts = new CancellationTokenSource())  
        {  
            var cancellationToken = cts.Token;  
  
            // Start the asynchronous operation with cancellation support  
            var task = PerformAsyncOperationWithCancellationAsync(cancellationToken);  
  
            // Simulate user input to cancel the operation after 2000 milliseconds  
            await Task.Delay(2000);  
            cts.Cancel();  
  
            try  
            {  
                await task;  
            }  
            catch (OperationCanceledException)  
            {  
                Console.WriteLine("Async operation canceled by user.");  
            }  
        }  
    }  
  
    static async Task PerformAsyncOperationWithCancellationAsync(CancellationToken cancellationToken)  
    {  
        Console.WriteLine("Start of async method with cancellation support.");  
  
        // Simulating a long-running asynchronous operation  
        await Task.Delay(5000, cancellationToken);  
  
        Console.WriteLine("End of async method with cancellation support.");  
    }  
}

在这里,我们将展示如何使用取消正在进行的异步操作。该方法支持取消。CancellationTokenPerformAsyncOperationWithCancellationAsync

  • using (var cts = new CancellationTokenSource()):创建一个 .CancellationTokenSource
  • await Task.Delay(5000, cancellationToken):模拟长时间运行的异步操作,支持取消。
  • await task:等待异步操作,处理操作是否取消。OperationCanceledException

C# 中的 Async/Await 为处理异步任务、提高代码可维护性和性能提供了优雅的解决方案。

无论是处理简单的延迟、异步运行同步方法、处理异常、同时管理多个任务,还是合并取消支持,Async/Await 都被证明是高级开发人员武器库中的多功能工具。将这些模式集成到代码库中可以增强涉及异步操作的方案中的响应能力和整体性能。

相关留言评论
昵称:
邮箱:
阅读排行