C#异步编程场景分为 I/O 绑定(例如从网络请求数据、访问数据库或读取和写入到文件系统)和 CPU 绑定(例如执行成本高昂的计算)。
I/O 绑定场景:从 Web 服务下载数据
对于 I/O 绑定代码,等待一个在 async
方法中返回 Task
或 Task<T>
的操作。
请使用 async
和 await
(而不使用 Task.Run
),不应使用任务并行库。
private readonly HttpClient _httpClient = new HttpClient();
downloadButton.Clicked += async (o, e) =>
{
// This line will yield control to the UI as the request
// from the web service is happening.
//
// The UI thread is now free to perform other work.
var stringData = await _httpClient.GetStringAsync(URL);
DoSomethingWithData(stringData);
};
CPU 绑定场景:为游戏执行计算
对于 CPU 绑定代码,等待一个使用 Task.Run 方法在后台线程启动的操作。
请使用 async
和 await
,但在另一个线程上使用 Task.Run
生成工作。如果该工作同时适用于并发和并行,还应考虑使用任务并行库。
private DamageResult CalculateDamageDone()
{
// Code omitted:
//
// Does an expensive calculation and returns
// the result of that calculation.
}
calculateButton.Clicked += async (o, e) =>
{
// This line will yield control to the UI while CalculateDamageDone()
// performs its work. The UI thread is free to perform other work.
var damageResult = await Task.Run(() => CalculateDamageDone());
DisplayDamage(damageResult);
};
原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/csharp/csharplang/11605.html