Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

how to to request the Task to stop working?

I'm using such code:

private Task[] tasks;
private volatile bool stayConnected;

....

tasks[i] = Task.Factory.StartNew(() =>
{
    while (stayConnected) {
        ...
    }
}

....

public void Disconnect()
{
    stayConnected = false;
    Task.WaitAll(tasks);
}

My code doesn't work - tasks never ends. I guess they do not receive fresh stayConnected = false value by some reason, probably just declaring field as volatile is not enough.

What is the correct way to signal a task to stop working? I don't want to "kill" the task, instead i want to "request" the task to finish.

I've found this article that suggests to use CancellationToken, should I use it or probably you can suggest something better? Can I use one CancellationToken for several tasks?

Also it's interesting why my initial code doesn't work.

Upvotes: 0

Views: 199

Answers (1)

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

It is better to use CancellationToken Structure but Boolean value.

CancellationTokenSource cts;
private Task[] tasks;

void Start()
{
    cts = new CancellationTokenSource();
    tasks = new Task[1];
    tasks [0] = Task.Run(() => SomeWork(cts.Token), cts.Token);
}

void SomeWork(CancellationToken cancellationToken)
{
    while (true)
    {
        // some work
        cancellationToken.ThrowIfCancellationRequested();
    }
}

void Cancel()
{
    cts.Cancel();
    Task.WaitAll(tasks);
}

Upvotes: 2

Related Questions