0

I am trying calling the async method SendParkInfo method using the await operator like this

await Task.WhenAny(parkList);and await Task.WhenAny(parkInfo);

parkInfo has SendParkInfo method object

Here is some part of my code.

    public async Task<AvailableParksResponse> GetAvailableParks(IEnumerable<string> parkRegionList)
    {
    //
        var parkList = parkRegionList.Select(x => SendParkInfo(x)).ToList();
        var parkListTask = await Task.WhenAny(parkList);
        response.ParkInfoList = new List<Task<ParkInfo>> { parkListTask };

        var parkInfo = SendParkInfo(id);
        var parkTask = await Task.WhenAny(parkInfo);
        response.ParkInfo = new List<Task<ParkInfo>> { parkTask };

    //
    }

    public virtual async Task<ParkInfo> SendParkInfo(string id) 
    {
    //
        var apiResponse = await apiClient.GetAsync(RequestUri + id);
    //
    }

Is it ok to call SendParkInfo like the way I am calling and then using await operator with Task.WhenAny method. Or is there any better way of calling the Async SendParkInfo method

Any help or suggestion would be appreciated.

Thanks in advance

8
  • There seem to be some compilation issues here. You are trying to redefine IEnumerable<string> parkList as an IList<Task<ParkInfo>>, is that intentional? Commented Sep 16, 2019 at 10:21
  • @NathanTaylor sorry I misunderstood your question. response.ParkInfoList is like this public IEnumerable<Task<ParkInfo>> ParkInfo { get; set; } Commented Sep 16, 2019 at 10:25
  • 2
    Your example is just too sparse. Where does id in GetAvailableParks come from? How is AvailableParksResponse used? How does it make sense to have list of parks, but only return the first one that completes? Commented Sep 16, 2019 at 10:26
  • Task.WhenAny() expects a collection of tasks, but you are using it with a single Task<ParkInfo>, passing it the result of SendParkInfo(id). Commented Sep 16, 2019 at 10:26
  • 1
    Why you need to use WhenAny? You can not await on SendParkInfo? Commented Sep 16, 2019 at 10:27

1 Answer 1

2

Task.WhenAny() will return a Task which is considered completed when at least one item in the list of tasks passed into WhenAny() has completed. This usually an appropriate option if you want to return data incrementally, as processing completes.

Alternatively, if your intent is to only return a result when all async tasks have completed, consider Task.WhenAll().

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

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.