How to implement cancellable worker thread
Posted
by Arnold Zokas
on Stack Overflow
See other posts from Stack Overflow
or by Arnold Zokas
Published on 2010-05-31T09:02:36Z
Indexed on
2010/05/31
9:02 UTC
Read the original article
Hit count: 275
Hi,
I'm trying to implement a cancellable worker thread using the new threading constructs in System.Threading.Tasks namespace. So far I have have come up with this implementation:
public sealed class Scheduler
{
private CancellationTokenSource _cancellationTokenSource;
public System.Threading.Tasks.Task Worker { get; private set; }
public void Start()
{
_cancellationTokenSource = new CancellationTokenSource();
Worker = System.Threading.Tasks.Task.Factory.StartNew(
() => RunTasks(_cancellationTokenSource.Token),
_cancellationTokenSource.Token
);
}
private static void RunTasks(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
Thread.Sleep(1000); // simulate work
}
}
public void Stop()
{
try
{
_cancellationTokenSource.Cancel();
Worker.Wait(_cancellationTokenSource.Token);
}
catch (OperationCanceledException)
{
// OperationCanceledException is expected when a Task is cancelled.
}
}
}
When Stop()
returns I expect Worker.Status
to be TaskStatus.Canceled
.
My unit tests have shown that under certain conditions Worker.Status
remains set to TaskStatus.Running
.
Is this a correct way to implement a cancellable worker thread?
© Stack Overflow or respective owner