Guerrilla
Guerrilla

Reputation: 14856

Make Entity Framework Linq query async

I have a function that populates a combo box in my winform app. The operation takes a few seconds so I'd like to make it async.

Here is the function:

public static List<string> GetAllPostCodeRegions(string country)
{
    using (var db = new PlaceDBContext())
    {
        var regions = db.PostCodes.Where(pc => pc.Country == country).OrderBy(pc => pc.Region).Select(pc => pc.Region).Distinct().ToList();

        return regions;
    }
}

I tried just adding in async keywords like below:

public async static Task<List<string>> GetAllPostCodeRegions(string country)
{
    using (var db = new PlaceDBContext())
    {
        var regions = db.PostCodes.Where(pc => pc.Country == country).OrderBy(pc => pc.Region).Select(pc => pc.Region).Distinct().ToList();

        return regions;
    }
}

But this isn't awaiting anything and the UI still locks when I call:

var regions = await DataFunctions.GetAllPostCodeRegions("UK");

How do I make this operation async and stop UI locking up?

Upvotes: 1

Views: 1555

Answers (1)

bto.rdz
bto.rdz

Reputation: 6720

you can Try .ToListAsync or:

public static Task<List<string>> GetAllPostCodeRegions(string country)
{
    return Task.Run(() => 
       {
          using (var db = new PlaceDBContext())
          {
               return db.PostCodes
                        .Where(pc => pc.Country == country)
                        .OrderBy(pc => pc.Region)
                        .Select(pc => pc.Region).Distinct().ToList();
          }
      });        
}

Upvotes: 1

Related Questions