You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF主线程调用WaitOne阻塞时为何仍能响应Deactivate事件?

WPF主线程阻塞时Activate/Deactivate事件仍触发的问题

在WPF应用中出现以下特殊现象:当主线程调用AutoResetEvent.WaitOne()进入阻塞状态后,若窗口失去焦点触发Window.Deactivate事件,其处理函数仍会在主线程中执行。

代码示例

private AutoResetEvent m_autoResetEvent;

public MainWindow()
{
    InitializeComponent();
    m_autoResetEvent = new AutoResetEvent(false);
}

private void Window_Deactivated(object sender, EventArgs e)
{
}

private void test_Click(object sender, RoutedEventArgs e)
{
    Task.Factory.StartNew(() =>
    {
        Thread.Sleep(1000000);
        m_autoResetEvent.Set();
    });

    m_autoResetEvent.WaitOne();
}

点击按钮后,主线程会在WaitOne()处阻塞,但此时窗口失活时,Window_Deactivated()方法仍会被主线程触发执行。

曾猜测这与WPF线程模型中的重入与锁定机制有关,但相关文档主要针对lock和通用Win32窗口消息,未明确覆盖这类事件的特殊逻辑。

另外,该现象仅发生在Window.Activate和Window.Deactivate事件上,其他窗口事件不会出现此情况,现提出以下疑问:

  • Activate/Deactivate事件是否具备特殊优先级?
  • 是否存在其他类似的特殊事件?

内容的提问来源于stack exchange,提问作者maximusmp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 19:40:07