我在使用NotifyIcons时发现了一个重入问题.重现起来非常简单,只需在表单上删除NotiftIcon,click事件应如下所示:
private bool reentrancyDetected;
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (reentrancyDetected) MessageBox.Show("Reentrancy");
reentrancyDetected = true;
lock (thisLock)
{
//do nothing
}
reentrancyDetected = false;
}
Run Code Online (Sandbox Code Playgroud)
同时启动后台线程会导致一些争用:
private readonly object thisLock = new object();
private readonly Thread bgThread;
public Form1()
{
InitializeComponent();
bgThread = new Thread(BackgroundOp) { IsBackground = true };
bgThread.Start();
}
private void BackgroundOp()
{
while (true)
{
lock (thisLock)
{
Thread.Sleep(2000);
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果您开始单击notifyicon,将弹出消息,指示重入.我知道为什么STA中的托管等待应该为某些窗口泵送消息的原因.但是我不确定为什么要通知notifyicon的消息.还有一种方法可以在进入/退出方法时避免使用一些布尔指示器进行抽吸吗?