且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用异步方法和Task.Run异步方法之间的区别

更新时间: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:

  1. 我不确定您的同步数据分析需要占用多少CPU,但是对于UI而言,足以使其变得无响应.
  2. 您没有在等待异步操作.它需要看起来像这样:

  1. I'm not sure how CPU intensive is your synchronous data analysis, but it may be enough for the UI to get unresponsive.
  2. 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);
}