等待内部实体框架上下文与外部之间有什么区别?

问题描述 投票:1回答:1

我试图在C#中以异步方式运行SQL存储过程。我找到了两个选项,我想了解两者之间的差异:

在离开using语句之前我必须等待,否则将处理上下文:

private async Task<List<Currency>> Test1Async()
{
    using (var dc = new LandmarkEntities())
    {
        return await Task.Run(() =>
        {
            return dc.get_currencies()
            .Select(x => new Currency
            {
                ExchangeRate = x.exchange_rate,
                Mnemonic = x.mnemonic,
            })
            .ToList();
        });
    }
}

或者我返回一个正在运行的异步任务,其中包含将在其他地方等待的实体框架上下文:

private Task<List<Currency>> Test2Async()
{
    return Task.Run(() =>
    {
        using (var dc = new LandmarkEntities())
        {
            return dc
                .get_currencies()
                .Select(x => new Currency
                {
                    ExchangeRate = x.exchange_rate,
                    Mnemonic = x.mnemonic,
                })
                .ToList();
        }
    });
}

由于get_currencies()是一个存储过程.ToListAsync();不能使用。

c# async-await entity-framework-6
1个回答
2
投票

你可以使用.ToListAsync();

private async Task<List<Currency>> Test2Async()
{
    using (var dc = new LandmarkEntities())
    {
        return await dc
            .get_currencies()
            .Select(x => new Currency
            {
                ExchangeRate = x.exchange_rate,
                Mnemonic = x.mnemonic,
            })
            .ToListAsync();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.