Search code examples
c#asynchronoustaskcontinuewith

How to use ContinueWith with this example


I have following async method that is supposed to get all strings I need based on a list passed into the method:

public async Task<List<string>> GetStrings(List selections)
{
    List<string> myList = new List<string>();
    TaskCompletionSource<List<string>> someStrings = new TaskCompletionSource<List<string>>();

    // Register/deregister event that is fired on each selection.
    // Once this event is received, I get its arguments from which I 
    // get string and add it to my list of strings.
    // Once the list count matches number of selections passed into the method,
    // TaskCompletionSource result is set.
    EventHandler<IDataNotification> onCallThatFiresCompleted = null;
    onCallThatFiresCompleted = (sender, e) =>
    {
        var myString = e.getString();
        myList.Add(myString);
        if (myList.Count == selections.Count)
        {
            MyObserver.DataNotification -= onCallThatFiresCompleted;
            someStrings.TrySetResult(myList);
        }
    };
    MyObserver.DataNotification += onCallThatFiresCompleted; 


    foreach (var sel in selections)
    {
        // This call fires onCallThatFiresCompleted event that when received 
        // will conteain string I need in its arguments.
        CallThatFires_MyEvent();
    }

    return await someStrings.Task; //await for the task
}

How would a caller of this method use Task.ContinueWith() to process returned List once the task is completed? I want to do something like this:

foreach(var s in returnedStringList)
{
  // do something with the string s
}

Solution

  • How to use ContinueWith with this example

    You don't. You use await:

    var returnedStringList = await GetStrings(..);
    foreach(var s in returnedStringList)
    {
      // do something with the string s
    }
    

    As I describe on my blog, await is superior in every way to ContinueWith for asynchronous code.