-1

I have this metod:

public async Task StartAsync(Task process)
{
    if (process is null)
    {
        throw new ArgumentNullException(nameof(process));
    }
    var loading = ...;
    await Task.WhenAll(process, loading).ContinueWith(t => EndProgress());
}

and is called via a command like so:

private async Task TestAsync()
{
    await StartAsync(new Task(async () =>
    {
        //just for testing purpose
        await Task.Delay(15000);
    }));
}
ExecuteDelegate = async param => await TestAsync();

where ExecuteDelegate is an Action<T> delegate used by command.

Why does the await Task.WhenAll line not waiting those 15 seconds from Task.Dalay?

Clemens
  • 123,504
  • 12
  • 155
  • 268
Gabriel Anton
  • 444
  • 1
  • 6
  • 14
  • 2
    Why not pass just Task.Delay to the StartAsync? You wrap it in yet another task. – Wiktor Zychla Jun 23 '20 at 14:43
  • 3
    also i would say you need to await for `StartAsync` in `TestAsync` – Guru Stron Jun 23 '20 at 14:44
  • 1
    Or do `private Task TestAsync() { return StartAsync(Task.Delay(15000)); }` – Clemens Jun 23 '20 at 14:45
  • 1
    [You should **never** use the task constructor](https://blog.stephencleary.com/2014/05/a-tour-of-task-part-1-constructors.html), and [*almost never* use `ContinueWith`](https://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html). – Stephen Cleary Jun 24 '20 at 01:01

2 Answers2

1

You need to await the call to StartAsync:

private async Task TestAsync()
{
    await StartAsync(new Task(async () =>
    {
        await Task.Delay(15000);
    }));
}

NOTE: You can also simplify your code by not creating the redundant Task:

private async Task TestAsync()
{
    await StartAsync(Task.Delay(15000));
}

Or even simpler:

private Task TestAsync()
{
    return StartAsync(Task.Delay(15000));
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
Sean
  • 60,939
  • 11
  • 97
  • 136
0

You shouldn't use the constructor to create a Task but the static Task.Run method:

private async Task TestAsync()
{
    await StartAsync(Task.Run(async () =>
    {
        //just for testing purpose
        await Task.Delay(15000);
    }));
}

The task returned by Task.Run can be awaited as expected.

mm8
  • 163,881
  • 10
  • 57
  • 88