更新时间:2021-07-14 09:31:45
它们不一样吗?我当时以为不用等待 调用异步方法会创建一个新线程.
Should not they be the same? I was thinking that not using await for calling an async method creates a new thread.
否,async
不会神奇地为其方法调用分配新线程. async-await
主要是关于利用自然异步API的优势,例如对数据库的网络调用或远程Web服务.
No, async
does not magically allocate a new thread for it's method invocation. async-await
is mainly about taking advantage of naturally asynchronous APIs, such as a network call to a database or a remote web-service.
使用Task.Run
时,显式使用线程池线程执行委托.如果您使用async
关键字标记方法,但在内部没有await
任何内容,它将同步执行.
When you use Task.Run
, you explicitly use a thread-pool thread to execute your delegate. If you mark a method with the async
keyword, but don't await
anything internally, it will execute synchronously.
我不确定您的SyncContacts()
方法实际上是做什么的(因为您没有提供它的实现),但是将其标记为async
本身将不会给您带来任何好处.
I'm not sure what your SyncContacts()
method actually does (since you haven't provided it's implementation), but marking it async
by itself will gain you nothing.
现在您已经添加了实现,我看到两件事:
Now that you've added the implementation, i see two things:
您没有在等待异步操作.它需要看起来像这样:
You're not awaiting your asynchronous operation. It needs to look like this:
private async Task SyncDataAsync(SyncMessage syncMessage)
{
if (syncMessage.State == SyncState.SyncContacts)
{
await this.SyncContactsAsync();
}
}
private Task SyncContactsAsync()
{
foreach(var contact in this.AllContacts)
{
// do synchronous data analysis
}
// ...
// AddContacts is an async method
return CloudInstance.AddContactsAsync(contactsToUpload);
}