我想在单个线程上“锁定”资源。我已经尝试了所有我能想到的锁定机制,但我无法做到这一点。
在下面的示例中,当 Timer 触发时,我不希望 DoSomething 中的代码在 ShowDialog 返回之前执行。我原以为 lock 语句只允许 Form2 的一个实例返回,但这实际上都在一个线程上运行,因此它不会阻止线程重新进入该代码块。
这是一些示例代码,这不是我面临的确切场景,但它说明了问题。在我的实际代码中,我从连接的设备接收事件,因此没有计时器。
要重现,请创建一个 Windows 窗体应用并添加 Form1 和 Form2。将此代码复制到 Form1 中:
public partial class Form1 : Form
{
Timer _timer = new Timer();
private static object _lock = new object();
public Form1()
{
InitializeComponent();
_timer.Tick += delegate { DoSomething(); };
_timer.Interval = 5000;
_timer.Start();
}
private void DoSomething()
{
lock (_lock)
{
Form2 form2 = new Form2();
form2.ShowDialog();
}
}
}
请您参考如下方法:
如果您使用 ThreadStaticAttribute,标志应该可以解决问题。
public partial class Form1 : Form
{
Timer _timer = new Timer();
[ThreadStatic]
bool inEvent = false;
public Form1()
{
InitializeComponent();
_timer.Tick += delegate { DoSomething(); };
_timer.Interval = 5000;
_timer.Start();
}
private void DoSomething()
{
// if you want to stay here and wait instead of exiting, you could do:
// while (inEvent);
if (!inEvent)
{
inEvent = true;
Form2 form2 = new Form2();
form2.ShowDialog();
inEvent = false;
}
}
}
