Skip to main content
 首页 » 编程设计

c#之WinForms 中的 Control.Invoke(timeout) 之类的东西

2024年02月13日21JustinYoung

我的应用程序中有一些仪表。有时,当 UI 繁忙时,我的仪表线程会停止等待更新某些仪表。在那种情况下,我只想放弃我的计划并尝试在下一次民意调查时更新指标。我目前使用 Control.Invoke 从我的数据轮询线程移动到 UI。我不想使用 BeginInvoke,因为我不想浪费宝贵的 UI 时间来更新仪表,因为只有最终值才是最重要的。如果我不能在 40 毫秒内进入 UI 线程,是否有其他方法可以在 UI 线程上调用代码以提早退出? Invoke 方法中的代码是必需的,还是有其他方法可以在主线程上调用方法?

请您参考如下方法:

没有可用的超时选项。一种选择是使用 BeginInvoke,但前提是前一条消息已被处理。这将需要线程同步,但可以类似地编写:

// using 
object syncObj = new object(); 
bool operationPending = false; 
 
while (operation) 
{ 
   // ... Do work 
 
   // Update, but only if there isn't a pending update 
   lock(syncObj) 
   { 
       if (!operationPending) 
       { 
           operationPending = true; 
           control.BeginInvoke(new Action( () => 
           { 
               // Update gauges 
 
               lock(syncObj) 
                  operationPending = false; 
           })); 
       } 
   } 
} 
 
// Update at the end (since you're last update might have been skipped) 
control.Invoke(new Action(UpdateGuagesCompleted)); 

虽然这不会超时,但它会阻止您将 UI 事件“淹没”到主线程上,因为一次只会处理一个操作。


编辑:作为Yaur mentioned , 这种方法也可以在不通过 Interlocked 锁定的情况下完成:

while (operation) 
{ 
    int pendingOperations = 0; 
    // ... Do work 
 
    // Update, but only if there isn't a pending update 
    if (0 == Interlocked.CompareExchange(ref pendingOperations, 1, 0)) 
    { 
        control.BeginInvoke(new Action( () => 
        {    
            // Update gauges 
 
            // Restore, so the next UI update can occur 
            Interlocked.Decrement(ref pendingOperations); 
        })); 
    }        
} 
 
// Update at the end (since you're last update might have been skipped) 
control.Invoke(new Action(UpdateGuagesCompleted));