我正在尝试使用System.Threading.Tasks命名空间中的新线程构造实现可取消的工作线程。 到目前为止,我已经想出了以下实现:
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.
}
}
}
当
Stop()
返回时,我期望Worker.Status
为TaskStatus.Canceled
。我的单元测试表明,在某些情况下,
Worker.Status
仍然设置为TaskStatus.Running
。这是实现可取消工作线程的正确方式吗?