我正在构建一个库,可能需要在其中写入私有方法。并不总是会有写。我想公开一个公共方法,当有写时,等待它完成然后继续。
这是我想在代码中实现的目标。
public class Class1
{
public static Object lockObject = new Object();
public static void Method1()
{
// If the object is locked then wait for the lock to be released,
// but don't take the lock.
if (Monitor.IsEntered(lockObject))
{
Monitor.Wait(lockObject);
// Here I want something which will wait for the lock to be released,
// but don't do lock.
// I think Monitor.Wait takes the lock on release
}
Method2();
}
public static void Method2()
{
//Some code
//Based on some condition
try
{
Monitor.Enter(lockObject);
}
finally
{
Monitor.Exit(lockObject);
}
//Some more code
}
}