【问题标题】:Where to set await in delegate action [duplicate]在委托操作中设置等待的位置[重复]
【发布时间】:2017-07-18 09:39:32
【问题描述】:
public enum SyncListsEnum
{
    Country = 1,
    Language = 2
}

public class SyncListsService
{
    private readonly WeCandidateContext _db;
    private readonly IRestClientFactory _factory;
    private readonly IConfigurationService _configService;

    private readonly Dictionary<SyncListsEnum, Action<IList<ExpandoObject>>> _syncLists;

    public SyncListsService(WeCandidateContext db, IRestClientFactory factory, IConfigurationService configService)
    {
        _db = db;
        _factory = factory;
        _configService = configService;

        _syncLists = new Dictionary<SyncListsEnum, Action<IList<ExpandoObject>>>()
        {
            {SyncListsEnum.Country, items =>{ new CountrySync(_db).SyncItems(items); _db.SaveChangesAsync();}},
            {SyncListsEnum.Language, items =>{ new LanguageSync(_db).SyncItems(items); _db.SaveChangesAsync();}}
        };
    }

    public async Task SyncList(string listName)
    {
        SyncListsEnum list;
        if (!Enum.TryParse(listName, true, out list)) return;


        // get list content from Recruiter 
        var items = await GetListFromRecruiter();
        // call a specific routine for each list to handle insert/update/delete 
        if (items != null)
        {
            // Synchronizes the local table with items retrieced from Recruiter.
            this._syncLists[list](items);
        }
    }
}

在这段代码中一切都是正确的,但我需要await _db.SaveChangesAsync() 而不是_db.SaveChangesAsync()。如果我将 await 运算符放在 _db.SaveChangesAsync() 前面,它会显示一个错误,例如 await 运算符只能在异步 lamda 表达式中使用强>。

现在我应该在哪里使用 async 关键字来解决这个错误。

【问题讨论】:

  • 我想返回Task 而不在委托中添加await 会更好

标签: c# asynchronous


【解决方案1】:

async放在你的lambda表达式前面,然后你就可以使用await了。见“can not await async lambda

【讨论】:

猜你喜欢
  • 2021-01-13
  • 1970-01-01
  • 2018-11-17
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多