1

I have an API that returns a list of shops from my database along with shops from Google Places API.

 IEnumerable<ShopInOfferDetails> modelApi = null;
 IEnumerable<ShopInOfferDetails> modelDb = null;

            await new TaskFactory()
                .StartNew(() =>
                {
                    modelApi = Service.GetShopsFromGoogleApi(g);

                })
                .ContinueWith(x =>
                {
                    modelDb = Service.GetShopsFromDb(g);
                });


var model = modelApi.Concat(modelDb);    
return model;

The thing is that it takes too long to get and process the results from Google API (I am doing some more work at the background) and I wonder if there is a way to get the first data from my database - to return this data to the client and only then to get more data from Google Api and Return again - in such way the client gets the first result fast and then the rest from Google API.

1
  • 1
    Both your calls do IO. One for the DB and one for Google. I'd suggest invoking them concurrently by using their naturally async API's, such are offered via HttpClient and many ORMs. Then you could await Task.WhenAll on both. Alternatively, @Damir's suggestion for creating two different calls may also work if you want to show the end user a result ASAP. Commented Apr 12, 2015 at 16:29

2 Answers 2

1

If I were you, I would create 2 different web API methods and call both of them asynchronously from the client. When each one of them returns, the client can immediately show the results - this would create the desired effect: the user would first see the results from the database and then the slower ones from Google API.

Sign up to request clarification or add additional context in comments.

1 Comment

I was thinking about this option but I would like to control the number of the results - If I get enough from my database I won't return from Google. If I won't find the solution that what I will do.
0

I'd refactor this a bit:

List<ShopInOfferDetails> items = new List<ShopInOfferDetails>();

List<Task<IEnumerable<ShopInOfferDetails>>> tasks = new List<Task<IEnumerable<ShopInOfferDetails>>>();
var task1 = Task.Run(() => {
    items.AddRange(Service.GetShopsFromGoogleApi(g));
    });
tasks.Add(task1);
var task2 = Task.Run(() => {
    items.AddRange(Service.GetShopsFromDb(g));
    });
tasks.Add(task2);

Task.WaitAll(tasks.ToArray());

return items;

Comments

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.