当我尝试运行下面的代码时,执行同步操作。 为什么?
我收到以下警告......
警告1此异步方法缺少'await'运算符并将同步运行。考虑使用'await'运算符等待非阻塞API调用,或'await Task.Run(...)'在后台线程上执行CPU绑定工作。
private async void btProcessa_Click(object sender, EventArgs e)
{
await ProcessaA();
await ProcessaB();
}
public async Task ProcessaA()
{
for (int i = 0; i <= 100; i++)
{
pbProcessoA.Value = i;
Thread.Sleep(500);
}
}
public async Task ProcessaB()
{
for (int i = 0; i <= 100; i++)
{
pbProcessoB.Value = i;
Thread.Sleep(500);
}
}
答案 0 :(得分:10)
async
并不意味着“在后台线程上运行此代码”。如果您想了解async
的更多信息,我有introductory blog post,MSDN docs很棒,而且full guide to the Task-based Asynchronous Pattern。
如果要对I / O绑定(或基于事件)的操作进行一些模拟,则应使用Task.Delay
而不是Thread.Sleep
:
public async Task ProcessaA()
{
for (int i = 0; i <= 100; i++)
{
pbProcessoA.Value = i;
await Task.Delay(500);
}
}
如果您想模拟CPU绑定操作,那么您应该通过Task.Run
将它们推送到后台任务:
public async Task ProcessaA()
{
for (int i = 0; i <= 100; i++)
{
pbProcessoA.Value = i;
await Task.Run(() => { Thread.Sleep(500); });
}
}
答案 1 :(得分:2)
我把这个例子写成了一个真实的生产系统。将实体保存在数据库中可能需要一些时间。看看这个优雅的模拟
class TestAsyncAwait
{
public void GetEntities()
{
for (int i = 0; i < 4; i++)
{
var a = getEntities(i);
saveEntitiesAsync(a);
}
Console.WriteLine("\nPress any key to close\n");
Console.ReadKey();
}
private List<string> getEntities(int i)
{
Console.Write("getting Entities for id={0}...", i);
Thread.Sleep(2000);
var r = new List<string> { i.ToString(), " Hello!" };
Console.WriteLine("done, has the Entities for id={0}\n", i);
return r;
}
async void saveEntitiesAsync(List<string> a)
{
var sb = new StringBuilder();
await Task.Run(() =>
{
Thread.Sleep(4000); // simulates long task
foreach (string s in a) sb.Append(s);
});
// shows the thread in action
Trace.WriteLine("saved: " + sb.ToString());
}
}