Domanda

I have a C# desktop application.

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'. 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?

È stato utile?

Soluzione

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. 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;
            }
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top