punkouter
punkouter

Reputation: 5356

How to wait for Tasks to finish with Task.WhenAll ?

This all works so far but there are 2 things that bother me and I think I am using the wrong way

Problem #1 - I only want to return a string but I seem forced to return a string ARRAY. How can I just make this return a string ?

   Task<string> taskVelocifyData = GetVelocifyData();
            string[] userEmail = await Task.WhenAll(taskVelocifyData);

Problem #2 - Not sure if this is a problem but is this the optimal to wait for async tasks to complete before going to the next async task ?

  private async void DispatcherTimer_Tick(object sender, object e)
    {
        List<string>[] photos = new List<string>[10];

        try
        {
            //Use Velocify API to get most recent lead
            Task<string> taskVelocifyData = GetVelocifyData();
            string[] userEmail = await Task.WhenAll(taskVelocifyData);

            //Ignore recent lead if it has not changed
            if (lsi.VelocifyLeadTitle != previousVelocifyLeadTitle)
            {
                //If there is an email, use FullContact API to get photos
                if (userEmail[0] != "")
                {
                    var taskFullContactData = GetFullContactData(userEmail[0]);
                     photos = await Task.WhenAll(taskFullContactData);

                    if (photos.Count() != 0)
                    {
                        var taskFaceData = GetFaceData(photos);
                    }

                }
                else
                {
                    lsi.FullContactPictures = new ObservableCollection<string>();
                }

                // DEBUG
                //   dispatcherTimer.Stop();

                LeadSpeakerItems.Add(lsi);

                SpeakData(leadSpeakerItems.Last().VelocifyLeadTitle);
            }

            previousVelocifyLeadTitle = lsi.VelocifyLeadTitle;
        }
        catch (Exception ex)
        {

        }

Upvotes: 1

Views: 1091

Answers (1)

Jakub Lortz
Jakub Lortz

Reputation: 14896

You have a single Task, so you can await it directly. You don't need Task.WhenAll.

string userEmail = await GetVelocifyData();

The Task.WhenAll method

Creates a task that will complete when all of the System.Threading.Tasks.Task objects in an enumerable collection have completed.

When completed, the task will return an array with results of all tasks passed to Task.WhenAll.

Upvotes: 7

Related Questions