为了提高代码稳定性,您还可以使用类 TriggerLock 而不是 ignoreEvents 标志。
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
using (new TriggerLock())
{
checkBox2.Checked = checkBox1.Checked;
checkBox3.Checked = checkBox1.Checked;
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (TriggerLock.IsOpened)
{
MessageBox.Show("Changed in 2");
}
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (TriggerLock.IsOpened)
{
MessageBox.Show("Changed in 3");
}
}
TriggerLock 类,它像信号量一样工作:
public class TriggerLock
: IDisposable
{
private static int _nUsing = 0;
private bool _bDisposed;
public TriggerLock()
{
_bDisposed = false;
Interlocked.Increment(ref _nUsing);
}
~TriggerLock()
{
Dispose(false);
}
public static bool IsOpened
{
get { return _nUsing == 0; }
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool bDisposing)
{
if (bDisposing && !_bDisposed)
{
Interlocked.Decrement(ref _nUsing);
_bDisposed = true;
}
}
}