【问题标题】:How can I do a Monitor.Wait with processing message queue?如何在处理消息队列时执行 Monitor.Wait?
【发布时间】:2015-12-08 17:00:45
【问题描述】:

我正在使用 .NET 4.0(无异步)。

我正在寻找Monitor.WaitApplication.Run 的组合。我浏览了对象资源管理器,但找不到。

它存在吗?如果没有,最好的实现方式是什么?

我仍然没有尝试过,因为我的想法很肮脏。像这样的东西:

while (!(timeOutHasBeenReached || aLockHasBeenAcquired))
{
    Application.DoEvents() ; 
}

为了避免XY问题,让我介绍一下最终目标(与单元测试有关):

using (ApplicationContext applicationContext = new ApplicationContext()) 
{
    using (Control control = new Control() { Visible = true } )
    {
        // control will do something across the web 
        // When the control has done it, it will raise an event invoking applicationContext.Exit() 
        // As a web connection is not always timing trustfull I'd like 
        // to specify a timeout (or eventually abort it with a Monitor.Pulse)

        Application.Run(applicationContext);         
    }
}

Control 是一个 Winform 组件,我无法修改,也不想这样做 Thread.Abort

【问题讨论】:

  • Application.DoEvents() 通常(并且多次错误地)用于“避免”多线程。那么你到底想做什么呢?
  • @yms : 我做了一个编辑
  • 你不能通过control.Invoke(() => Application.Exit()); 中止吗?或者只是 control.Close(); 或 Dispose。
  • @usr :是的,我可以做到。谢谢

标签: c# multithreading winforms monitor


【解决方案1】:

你不能通过control.Invoke(() => Application.Exit()); 中止吗?或者只是control.Close();Dispose

【讨论】:

  • 我会这样做的。真正的问题是我被同步方式卡住了。
猜你喜欢
  • 2023-02-10
  • 2021-08-22
  • 2015-12-16
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多