What are the differences between awaiting inside entity framework context and outside?

async-await c# entity-framework-6

Question

I am trying to run a SQL stored procedure in an async way in C#. I have found two options and I would like to understand the differences between the two:

I have to await before getting out of the using statement else the context would be disposed:

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();
        });
    }
}

Or I return a running async task containing the entity framework context which will be awaited somewhere else:

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();
        }
    });
}

As get_currencies() is a stored procedure .ToListAsync(); cannot be used.

1
1
9/17/2018 9:32:17 AM

Popular Answer

You could use .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();
    }
}
2
9/17/2018 8:37:56 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow