【问题标题】:Why some async methods have async while other don't为什么有些异步方法有异步而另一些没有
【发布时间】:2015-03-24 19:10:56
【问题描述】:

我试图了解何时使用等待/异步。 在网上阅读了几篇文章后,我开始分析 Asp.Net Identity 源代码。这是 RoleStore.cs 的有趣片段

https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.EntityFramework/RoleStore.cs

    /// <summary>
    ///     Find a role by name
    /// </summary>
    /// <param name="roleName"></param>
    /// <returns></returns>
    public Task<TRole> FindByNameAsync(string roleName)
    {
        ThrowIfDisposed();
        return _roleStore.EntitySet.FirstOrDefaultAsync(u => u.Name.ToUpper() == roleName.ToUpper());
    }

    /// <summary>
    ///     Insert an entity
    /// </summary>
    /// <param name="role"></param>
    public virtual async Task CreateAsync(TRole role)
    {
        ThrowIfDisposed();
        if (role == null)
        {
            throw new ArgumentNullException("role");
        }
        _roleStore.Create(role);
        await Context.SaveChangesAsync().WithCurrentCulture();
    }

我的问题是: 为什么FindByNameAsync 没有async 关键字而CreateAsync 有?

我们可以这样写

 public async Task<TRole> FindByNameAsync(string roleName)
     {
        ThrowIfDisposed();
        return await _roleStore.EntitySet.FirstOrDefaultAsync(u => u.Name.ToUpper() == roleName.ToUpper());
    }

这将编译。我认为这是不正确的,但我不知道为什么。

【问题讨论】:

  • 因为FindByNameAsync 没有awaitCreateAsync 有任何作用。

标签: c# asp.net entity-framework asynchronous


【解决方案1】:

在代码中使用关键字await时,只需要使用关键字async即可。您的第一个代码 sn-p 不使用await,因此不需要async

第二个片段使用await 的原因可能是.WithCurrentCulture(); 方法正在做一些特殊的事情,因此该方法中的await 将使用的SynchronizationContext 将在其中存储某种文化信息.

【讨论】:

    【解决方案2】:

    它没有被标记为async,因为它不需要await

    是的,您可以将其标记为asyncawait 任务。它不会破坏任何东西(好吧,当在已处置的对象上调用时,它确实会巧妙地改变错误处理语义),但也没有理由这样做。你会不遗余力地添加一些毫无成效的工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-05
      • 2017-01-03
      • 2011-09-12
      • 2015-02-27
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      相关资源
      最近更新 更多