2

I have a form with a button and a list box. I want to add to the list box the results from two functions. These two functions can take an unknown amount of time to complete and I want to execute them simultaneously. As soon as either of the functions completes the computation, I want to display the result in the list box (before the other function completed). At the moment, the results are displayed after both functions complete. I wouldn't mind if the functions update the list box themselves.

    async Task<string> LongTaskAsync()
    {
        for(int i = 0; i < 50; i++) {
            Thread.Sleep(100);
        }

        return "Completed long task async";
    }

    async Task<string> ShortTaskAsync()
    {
        for(int i = 0; i < 5; i++) {
            Thread.Sleep(100);
        }

        return "Completed short task async";
    }

    async void BtnRunClick(object sender, EventArgs e)
    {
        listBox1.Items.Clear();

        var longTask = Task.Run(() => LongTaskAsync());
        var shortTask = Task.Run(() => ShortTaskAsync());

        listBox1.Items.Add(await longTask);
        listBox1.Items.Add(await shortTask);        
    }
4
  • 1
    Don't use Thread.Sleep with tasks. Use Task.Delay and await that.
    – Joelius
    Nov 16, 2019 at 10:56
  • 1
    Thanks for suggestion, I'll do that in the future. For this example, I don't think it matters.
    – Nick_F
    Nov 16, 2019 at 11:00
  • 1
    Yea I know it doesn't solve anything regarding the question but I'm just saying :)
    – Joelius
    Nov 16, 2019 at 11:04
  • 1
    I don't have time to answer right now but take a look at ContinueWith, I think you can solve it with that.
    – Joelius
    Nov 16, 2019 at 11:08

3 Answers 3

3

The reason why it shows 2 of them at the same time related how you chain your awaits.

 listBox1.Items.Add(await longTask);
 listBox1.Items.Add(await shortTask); 

You are awaiting longer task before the shorter one. The second line runs after long task done its work in this time shorter one was already completed that's why you see them at the same time. But in a world you don't know what task will take longer to execute you need to have a better solution.

  Action<Task<string>> continuationFunction = t => { this.listBox1.Items.Add(t.Result); };
  Task.Run(() => LongTaskAsync()).ContinueWith(continuationFunction, TaskScheduler.FromCurrentSynchronizationContext()); 
  Task.Run(() => ShortTaskAsync()).ContinueWith(continuationFunction, TaskScheduler.FromCurrentSynchronizationContext());

TaskScheduler.FromCurrentSynchronizationContext() is for to avoid cross thread access exceptions.

0
3

You don't have to use ContinueWith for this. It's almost always possible to avoid mixing async/await and ContinueWith-style of continuations. In your case, it can be done like this:

async void BtnRunClick(object sender, EventArgs e)
{
    listBox1.Items.Clear();

    async Task longTaskHelperAsync() {
        // probably, Task.Run is redundant here,
        // could just do: var item = await LongTaskAsync();
        var item = await Task.Run(() => LongTaskAsync()); 
        listBox1.Items.Add(item);
    }

    async Task shortTaskHelperAsync() {
        // probably, Task.Run is redundant here, too
        var item = await Task.Run(() => ShortTaskAsync()); 
        listBox1.Items.Add(item);
    }

    await Task.WhenAll(longTaskHelperAsync(), shortTaskHelperAsync());
}

I believe this way it's more readable and you don't have to worry about synchronization context, FromCurrentSynchronizationContext, etc.

Also, most likely you'd want to take care of possible re-entrancy, if BtnRunClickis clicked again while those async ctasks are still in-flight.

7
  • Thanks Noseratio. It works and it looks more digestible than the other code. I think you placed the two async functions by mistake inside the BtnRunClick function.
    – Nick_F
    Nov 16, 2019 at 11:57
  • @Nick_F, are you targeting C# 7.0+, which has support for local functions?
    – noseratio
    Nov 16, 2019 at 11:58
  • @Nick_F, then you can still use async lambdas for local functions: Func<Task> longTaskHelperAsync = async () => { ... };
    – noseratio
    Nov 16, 2019 at 12:01
  • 1
    Yes, I moved the two local functions outside and it runs fine.
    – Nick_F
    Nov 16, 2019 at 12:03
  • @Nick_F, yes it's a good idea to move them out if you can. The only reason I used local functions was to show that you can do pretty much everything you could with ContinueWith lambdas, including having access to local variables.
    – noseratio
    Nov 16, 2019 at 12:08
1

You could solve it a bit more generically by creating a method that awaits a task, and also adds the result of the task to the ListBox.

async Task ProcessAndAddToListAsync(Func<Task<string>> function)
{
    var value = await Task.Run(function); // Start the task in a background thread
    listBox1.Items.Add(value); // Update the control in the UI thread
}

Then use this method inside the event handler of the button-click event:

async void BtnRunClick(object sender, EventArgs e)
{
    listBox1.Items.Clear();

    var longTask = ProcessAndAddToListAsync(LongTaskAsync);
    var shortTask = ProcessAndAddToListAsync(ShortTaskAsync);

    await Task.WhenAll(longTask, shortTask); // optional
    // Here do anything that depends on both tasks being completed
}
5
  • Thank you Theodor, this solution is even better - only one additional function was needed.
    – Nick_F
    Nov 24, 2019 at 12:47
  • It appears I can change the return type of the functions LongTaskAsync() and ShortTaskAsync() to string and I still got the desired outcome. They should be renamed LongTask() and ShortTask(). The original functions, the way I created them lack the await operator anyway.
    – Nick_F
    Nov 24, 2019 at 12:54
  • @Nick_F yeap, Task.Run is a versatile method, and can handle sync and async delegates equally well. Nov 24, 2019 at 14:14
  • Theodor, if my functions have arguments, how do I call them from Task.Run?
    – Nick_F
    Nov 29, 2019 at 8:56
  • @Nick_F You could use lambdas to pass ad hoc arguments: ProcessAndAddToListAsync(() => LongTaskAsync(arg1, arg2)) Nov 29, 2019 at 9:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.