在委托行动中设置等待的位置

时间:2017-02-27 16:58:34

标签: c# asynchronous

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运算符只能在async lamda表达式中使用

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

1 个答案:

答案 0 :(得分:1)

async放在lambda表达式前面,然后可以使用await。请参阅“can not await async lambda