shi*_*hiv 1 c# compact-framework
我正在使用 c# 紧凑框架和 vs2008。我面临 Lock 语句的问题。我的应用程序大部分时间都可以运行,但有时仍然挂起。
我尝试过这些
1) Lock(this)
2) lock (Core.Processor.Input.GPSIDInput.gps)
3) Monitor.TryEnter(Core.Processor.Input.GPSIDInput.gps);
try{}
finally{ Monitor.Exit(this); }
Run Code Online (Sandbox Code Playgroud)
为什么当我使用“try catch 块”时锁定失败时它不会出来。
GPS定位系统
[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
}
}
Run Code Online (Sandbox Code Playgroud)
GPSID输入.cs
namespace Core.Processor.Input
{
public class GPSIDInput
{
.......
public static Gps gps = new Gps();
public static void CloseGPS()
{
gps.Close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Lock就像临界区一样工作。只有一个线程可以“持有锁”。当一个线程这样做时,尝试持有锁的另一个线程必须等待,直到另一个线程释放它。不存在锁“失败”这样的事情,它只是等待持有它的线程释放它。