Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 251
Adam Heeg Avatar asked May 04 '16 14:05

Adam Heeg


1 Answers

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();    
like image 64
i3arnon Avatar answered Oct 05 '22 23:10

i3arnon