空锁以保证线程完成

时间:2017-06-07 10:37:34

标签: c# multithreading locking

我的c#服务看起来像这样:

public partial class MyService : ServiceBase 
{
    private object @lock = new object();
    private CancellationTokenSource cancellationSource = new CancellationTokenSource();
    private Timer timer = new Timer(Worker, null, 0, 20*1000);

    private void Worker(Object stateInfo)
    {
        lock (@lock) {
            if (cancellationSource.IsCancellationRequested)
                return;

            //code that must not execute after OnStop

        }
    }

    protected override void OnStop()
    {
        cancellationSource.Cancel();

        lock (@lock) {}

        //Worker is guaranteed not to execute any more code here
    }

}

正如您所看到的,Worker不应该在OnStop之后再运行任何代码,我认为空锁会对其进行排序,因为即使Worker在其后输入锁定,它也会立即退出,因为取消令牌。

但是我从未见过空锁,所以我担心我错过了什么。我有吗?

1 个答案:

答案 0 :(得分:0)

lock在这里没有任何目标。使用Task

可以更好地完成您要实现的目标
Task.Run(Worker, cancellationToken);

如果计时器被点击,取消令牌将立即停止任务进一步运行。