面试题答案
一键面试基本步骤
- 定义异步方法:使用
async
关键字标记方法,表明该方法是异步的。 - 调用异步操作:在异步方法内部,使用
await
关键字来暂停当前方法的执行,直到被等待的异步操作完成。await
只能在async
方法内部使用。 - 处理返回结果:当异步操作完成后,
await
表达式会返回操作的结果(如果有)。
示例代码
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
// 原同步方法
static void DownloadFile(string url, string filePath)
{
using (var client = new WebClient())
{
client.DownloadFile(url, filePath);
}
}
// 改造后的异步方法
static async Task DownloadFileAsync(string url, string filePath)
{
using (var client = new HttpClient())
{
var data = await client.GetByteArrayAsync(url);
await File.WriteAllBytesAsync(filePath, data);
}
}
static async Task Main()
{
string url = "http://example.com/file.txt";
string filePath = "localFile.txt";
await DownloadFileAsync(url, filePath);
Console.WriteLine("文件下载完成");
}
}
在上述示例中:
DownloadFileAsync
方法被标记为async
,表示这是一个异步方法。await client.GetByteArrayAsync(url)
等待从网络获取文件内容的异步操作完成,并返回字节数组。await File.WriteAllBytesAsync(filePath, data)
等待将字节数组写入本地文件的异步操作完成。- 在
Main
方法中,通过await DownloadFileAsync(url, filePath)
调用异步下载方法,并等待其完成。