简体   繁体   English

使用静态对象时如何避免锁定

[英]How to avoid locking when using a static object

I have a C# desktop application. 我有一个C#桌面应用程序。

In my code I am acquiring an image from a camera. 在我的代码中,我正在从相机获取图像。 I pass this image to a routine. 我将此图像传递给例程。

This is the 'syntax' of my code: 这是我的代码的“语法”:

//in a routine
if (!isProcessingMotion)
{
    try
    {
        isProcessingMotion = true;
        //do  stuff
    }
    finally
    {
        isProcessingMotion = false;
    }
}
//////

//module variable:
private static bool isProcessingMotion = false;

The function is reached when an event is raised from the parent code. 从父代码引发事件时,将达到该功能。

The trouble is the 'isProcessingMotion = false is not always 'hit'. 问题是'isProcessingMotion = false并不总是'hit'。 I have put a try-catch around the whole of the code but there is no error. 我在整个代码中都进行了尝试捕获,但是没有错误。

I do not want to use monitor or lock('a read only static object') as when I do the app grinds down to a slow process. 我不想使用监视程序或锁定(“只读静态对象”),因为当我执行该应用程序时,它会缓慢运行。

What should I be looking out for? 我应该注意什么?

I presume what is happening is not that the finally block isn't reached, it is that a different thread might be changing the isProcessingMotion variable after that finally block has executed. 我想发生的事情不是不是未到达finally块,而是在执行了finally块之后,另一个线程可能正在更改isProcessingMotion变量。 That might happen when a second event is fired, but the first event hasn't finished processing the first request. 当触发第二个事件,但是第一个事件尚未完成对第一个请求的处理时,可能会发生这种情况。

It seems that there are multiple accesses to your field at one. 似乎一次访问您的字段有多个权限。 Although you prefer not to use a lock, this seems like the perfect fix for your problem. 尽管您不希望使用锁,但这似乎是解决问题的完美方法。 Either that or you'll have to change your application logic to not make multiple reads to that same variable. 要么这样做,要么您必须更改应用程序逻辑以不对同一变量进行多次读取。

Edit 编辑

Since you have to process them sequentially, i'd definitely go with a lock: 由于您必须按顺序处理它们,因此我绝对会锁定:

        var processingLock = new object();
        if (!isProcessingMotion)
        {
            lock (processingLock)
            {
                isProcessingMotion = true;
                // Do stuff..

                isProcessingMotion = false;
            }
        }

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

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