1

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?

2
  • 1
    You need to call ToListAsync() instead of ToList() and add an await in front of that statement. This requires Entity Framework 6 or higher. Commented Sep 3, 2015 at 3:35
  • 1
    Thanks. I also needed to add using System.Data.Entity as using the ctrl + period didn't suggest it for some reason. Commented Sep 3, 2015 at 3:51

1 Answer 1

1

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();
          }
      });        
}
Sign up to request clarification or add additional context in comments.

1 Comment

I said both options, make it by your self is not that hard

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.