简体   繁体   English

如何让锁等到它被释放?

[英]How to make lock wait until it is freed?

I am using Lock to access a queue, but one of the cases seems to never execute the block of code inside of lock I have one thread that will execute the following code every few seconds我正在使用 Lock 访问队列,但其中一种情况似乎永远不会执行 lock 内的代码块我有一个线程将每隔几秒钟执行以下代码

lock(queueLock){ 
    while(queue.Count > 0){
        doSomething(queue.Dequeue());
    }
}

And another thread that will execute the following code depending on I/O(Not determined by time interval):另一个线程将根据 I/O 执行以下代码(不由时间间隔决定):

lock(queueLock){
   queue.Enqueue(input);       
}

This second one never getes to execute the code inside the lock.第二个永远不会执行锁内的代码。 I already tried to use the debugger or prints, but this just seems to run and on the threads window of the VS debugger it looks like the thread just died after trying to acquire the lock while no other thread was even using this queue.我已经尝试使用调试器或打印件,但这似乎只是在运行,并且在 VS 调试器的线程窗口上,看起来线程在尝试获取锁后刚刚死亡,而没有其他线程甚至使用此队列。

I am not using .net I am programming on unity, but in this case I am not using anything unity specific besides the update function.我没有使用 .net 我正在统一编程,但在这种情况下,除了更新功能之外,我没有使用任何特定于统一的东西。

尝试使用没有锁的线程安全ConcurrentQueue

最后,问题不在于锁,实际上只是队列锁之前的一行代码,我将 e 从 json 转换到另一个类,最终抛出了一个异常,表明统一没有向我展示,但是因为在我最终找错了地方之前,我从未在 c# 中使用过多线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM