你听说过“经验丰富的”开发人员这个词吗?
这是一个在他身上有盐和胡椒的开发商。
好的 好的。对不起,我再也忍不住了。我知道,我很有趣。
顺便说一句,既然我已经开起了我的笑话,那就是过去两天的烹饪,是时候专注于下一个高级软件面试问题了。
我们将探讨的问题是:
Async/Await takes 如何在 .NET 中工作?
我还整理了几个例子来帮助你更好地理解这些想法。
如果您想在 Medium 中获得更多最佳笑话,请邀请您从我的个人资料订阅我的时事通讯。您将收到我下一篇文章的电子邮件通知。
现在,将您的战利品放在一个舒适的位置,让我们开始吧!
Async/Await 是编程中的一项强大功能,可简化异步编程,使其更具可读性和可维护性。
如今,它几乎可以在任何地方找到。从python,unity,C++,JS到C#/.NET。
在处理可能需要时间才能完成的任务(如 I/O 操作或网络请求)时,它特别有用。
在本文中,我们将深入探讨 .NET 中 Async/Await 任务的基础知识,并提供 C# 中的五个实际示例。
Async 和 Await 是协同工作以在 C# 中创建异步代码的关键字。
修饰符在方法签名中用于指示方法包含异步操作,并用于指示异步操作发生的位置。asyncawait
当异步方法遇到关键字时,它会将当前线程释放回调用代码,从而允许它执行其他任务。等待的操作完成后,该方法将从中断的位置恢复执行。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
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
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
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
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
C# 中的 Async/Await 为处理异步任务、提高代码可维护性和性能提供了优雅的解决方案。
无论是处理简单的延迟、异步运行同步方法、处理异常、同时管理多个任务,还是合并取消支持,Async/Await 都被证明是高级开发人员武器库中的多功能工具。将这些模式集成到代码库中可以增强涉及异步操作的方案中的响应能力和整体性能。