桂再入与托管等待 [英] Gui reentrancy with managed waiting

查看:100
本文介绍了桂再入与托管等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用NotifyIcons时,我发现了重入问题.复制非常容易,只需在表单上放置一个NotiftIcon,然后单击事件应如下所示:

I've found a reentrancy problem when using NotifyIcons. It's really easy to reproduce, just drop a NotiftIcon on a form and the click event should look like this:

private bool reentrancyDetected;
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
    if (reentrancyDetected) MessageBox.Show("Reentrancy");
    reentrancyDetected = true;
    lock (thisLock)
    {
        //do nothing
    }
    reentrancyDetected = false;
}

还启动一个后台线程,这将引起一些争用:

Also start a background thread which will cause some contention:

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);
        }
    }
}

现在,如果您开始单击notifyicon,则会弹出消息,指示重新进入. 我知道为什么STA中的托管等待应该为某些窗口泵送消息的原因.但是我不知道为什么会发出notifyicon的消息.还有没有一种方法可以避免在进入/退出方法时不使用某些布尔指示符的抽水?

Now if you start clicking on the notifyicon the message will pop up, indicating the reentrancy. I'm aware of the reasons why managed waiting in STA should pump messages for some windows. But I'm not sure why the messages of notifyicon are pumped. Also is there a way to avoid the pumping without using some boolean indicators when entering/exiting methods?

推荐答案

如果您替换Debugger.Break的MessageBox.Show调用,并在击中中断时启用了本机调试,请附加调试器,可以看到发生了什么.调用堆栈如下所示:

You can see what's happening if you replace the MessageBox.Show call by Debugger.Break and attach a debugger with native debugging enabled when the break hits. The call stack looks like this:

WindowsFormsApplication3.exe!WindowsFormsApplication3.Form1.notifyIcon1_MouseClick(object sender = {System.Windows.Forms.NotifyIcon}, System.Windows.Forms.MouseEventArgs e = {X = 0x00000000 Y = 0x00000000 Button = Left}) Line 30 + 0x1e bytes   C#
System.Windows.Forms.dll!System.Windows.Forms.NotifyIcon.OnMouseClick(System.Windows.Forms.MouseEventArgs mea) + 0x6d bytes 
System.Windows.Forms.dll!System.Windows.Forms.NotifyIcon.WmMouseUp(ref System.Windows.Forms.Message m, System.Windows.Forms.MouseButtons button) + 0x7e bytes   
System.Windows.Forms.dll!System.Windows.Forms.NotifyIcon.WndProc(ref System.Windows.Forms.Message msg) + 0xb3 bytes 
System.Windows.Forms.dll!System.Windows.Forms.NotifyIcon.NotifyIconNativeWindow.WndProc(ref System.Windows.Forms.Message m) + 0xc bytes 
System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.Callback(System.IntPtr hWnd, int msg = 0x00000800, System.IntPtr wparam, System.IntPtr lparam) + 0x5a bytes  
user32.dll!_InternalCallWinProc@20()  + 0x23 bytes  
user32.dll!_UserCallWinProcCheckWow@32()  + 0xb3 bytes  
user32.dll!_DispatchClientMessage@20()  + 0x4b bytes    
user32.dll!___fnDWORD@4()  + 0x24 bytes 
ntdll.dll!_KiUserCallbackDispatcher@12()  + 0x2e bytes  
user32.dll!_NtUserPeekMessage@20()  + 0xc bytes 
user32.dll!__PeekMessage@24()  + 0x2d bytes 
user32.dll!_PeekMessageW@20()  + 0xf4 bytes 
ole32.dll!CCliModalLoop::MyPeekMessage()  + 0x30 bytes  
ole32.dll!CCliModalLoop::PeekRPCAndDDEMessage()  + 0x30 bytes   
ole32.dll!CCliModalLoop::FindMessage()  + 0x30 bytes    
ole32.dll!CCliModalLoop::HandleWakeForMsg()  + 0x41 bytes   
ole32.dll!CCliModalLoop::BlockFn()  - 0x5df7 bytes  
ole32.dll!_CoWaitForMultipleHandles@20()  - 0x51b9 bytes    
WindowsFormsApplication3.exe!WindowsFormsApplication3.Form1.notifyIcon1_MouseClick(object sender = {System.Windows.Forms.NotifyIcon}, System.Windows.Forms.MouseEventArgs e = {X = 0x00000000 Y = 0x00000000 Button = Left}) Line 32 + 0x14 bytes   C#

相关函数是CoWaitForMultipleHandles.它确保STA线程在不仍然泵送消息的情况下也不会阻塞同步对象.这很不健康,因为它很可能导致死锁.特别是在NotifyIcon的情况下,因为阻止通知消息将使托盘窗口挂起,从而使所有图标均无效.

The relevant function is CoWaitForMultipleHandles. It ensures that the STA thread cannot block on a sync object without still pumping messages. Which is very unhealthy since it is so likely to cause deadlock. Especially in the case of NotifyIcon since blocking the notification message would hang the tray window, making all icons inoperative.

接下来看到的是COM模态循环,它臭名昭著地引起了重新进入问题.请注意,它是如何调用PeekMessage()的,这就是MouseClick事件处理程序再次被激活的方式.

What you see next is the COM modal loop, infamous for causing re-entrancy problems. Note how it calls PeekMessage(), that's how the MouseClick event handler gets activated again.

此调用堆栈的惊人之处在于,没有证据表明 lock 语句会转换为调用CoWaitForMultipleHandles的代码.它是由Windows本身以某种方式完成的,我相当确定CLR没有任何相关规定.至少不是SSCLI20版本.它表明Windows实际上具有一些有关CLR如何实现Monitor类的内置知识.非常棒的东西,不知道他们如何使它起作用.我怀疑它修补了DLL入口点地址以重新编码代码.

What's pretty stunning about this call stack is that there's no evidence of the lock statement transitioning into code that calls CoWaitForMultipleHandles. It is somehow done by Windows itself, I'm fairly sure that the CLR doesn't have any provisions for it. At least not in the SSCLI20 version. It suggests that Windows actually has some built-in knowledge of how the CLR implements the Monitor class. Pretty awesome stuff, no clue how they could make that work. I suspect it patches DLL entrypoint addresses to revector the code.

任何人,这些特殊对策仅在NotifyIcon通知运行时生效.一种解决方法是将事件处理程序的操作延迟到回调完成之前.像这样:

Anyhoo, these special counter-measures are only in effect while the NotifyIcon notification runs. A workaround is to delay the action of the event handler until the callback is completed. Like this:

    private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) {
        this.BeginInvoke(new MethodInvoker(delayedClick));
    }
    private void delayedClick() {
        if (reentrancyDetected) System.Diagnostics.Debugger.Break();
        reentrancyDetected = true;
        lock (thisLock) {
            //do nothing
        }
        reentrancyDetected = false;
    }

问题解决了.

这篇关于桂再入与托管等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆