Search code examples
c#compact-framework

Application hangs on Lock statement


I am Working with c# compact framework and vs2008. I am facing the issue on Lock statement. My application works most of the time but still hangs sometimes.

I tried these

1) Lock(this)
2) lock (Core.Processor.Input.GPSIDInput.gps)
3) Monitor.TryEnter(Core.Processor.Input.GPSIDInput.gps);
try{}
finally{ Monitor.Exit(this); }

Why is it not coming out when the lock fails as i am using "try catch block".

Gps.cs

[DllImport("coredll.dll")]
static extern int CloseHandle(IntPtr hObject);

public void Close()
{
    try
    {
        lock (Core.Processor.Input.GPSIDInput.gps)
        {

            if (newLocationHandle != IntPtr.Zero){
            CloseHandle(newLocationHandle);
            newLocationHandle = IntPtr.Zero;
            }......

        }
    }
    catch (Exception excpt)
    {
    //stack trace
    }
}

GPSIDInput.cs

namespace Core.Processor.Input
{
    public class GPSIDInput
    {
        .......
        public static Gps gps = new Gps();

        public static void CloseGPS()
        {
            gps.Close();
        }
    }
}

Solution

  • Just a guess to solve the problem if you are only worried that two threads try to release the handle at the same time then use something like this:

    object closeLockObj = new object();
    public void Close()
    {
        try
        {
            lock (closeLockObj)
            {
    
                if (newLocationHandle != IntPtr.Zero){
                CloseHandle(newLocationHandle);
                newLocationHandle = IntPtr.Zero;
                }......
    
            }
        }
        catch (Exception excpt)
        {
        //stack trace
        }
    }
    

    if other code aquires a lock on Core.Processor.Input.GPSIDInput.gps it could result in your application hanging. So its better to use a seperate lockObject