执行同步代码异步
如果要异步执行同步代码(例如 CPU 扩展计算),可以使用 Task.Run(() => {})
。
public async Task DoStuffAsync()
{
await DoCpuBoundWorkAsync();
}
private async Task DoCpuBoundWorkAsync()
{
await Task.Run(() =>
{
for (long i = 0; i < Int32.MaxValue; i++)
{
i = i ^ 2;
}
});
}