Adam Heeg
Adam Heeg

Reputation: 1714

Why is this Task not Finishing before my code passes the Wait Command

I have a task which runs a loop and delays for an interval each iteration. Once the CancellationTokenSource calls Cancel() I want my main code to Wait() for the Task.Delay(interval) to finish and the task to exit the loop before my code continues. I thought this code would work but it doesn't.

Instead my main code passes the t.Wait() before the Loop exits. Why?

Main Method Code:

var cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;

var t = Task.Run(() => { MyLoopTask(200, ct); });

// Prepare information

cts.Cancel();
t.Wait();    

// Send Information

Task Code

private async Task MyLoopTask(int interval, CancellationToken cancelToken)
{
    while (!cancelToken.IsCancellationRequested)
    {
        Debug.Print("   Still In Loop     ");
        // Do something
        await Task.Delay(interval);
    }

    Debug.Print("   cancelled     ");
    //Clean up
}

Upvotes: 6

Views: 306

Answers (1)

i3arnon
i3arnon

Reputation: 116636

You create a task with Task.Run that fires and forgets the actual task you get back from MyLoopTask.

Task.Run is redundant here. You can just call MyLoopTask and use the task it returns.

var t = MyLoopTask(200, ct);
// ...
t.Wait();

If you still have some reason to use Task.Run you can do so by making sure the delegate waits for the actual task by awaiting it:

var t = Task.Run(async () => await MyLoopTask(200, ct));
// ...
t.Wait();    

Upvotes: 9

Related Questions