control.BeginInvoke()未能调用委托

问题描述:

我注意到control.BeginInvoke(委托)有时无法调用委托。我知道BeginInvoke只是创建一个PostMessage,并且该消息稍后由应用程序处理(默认情况下,邮件限制为10,000)。鉴于我们的应用程序不是非常复杂,是否有任何其他原因可能无法执行委托?我的代码如下所示。control.BeginInvoke()未能调用委托

class MyClass : Form{ 

    private bool executing = false; 
    private delegate void DelegateBar(string info, int total, bool status, object obj); 
    private void Bar(string info, int total, bool status, object obj){ 
     log("Enterning Bar"); 
     // Update something on UI 
     executing = false; 
     log("Exiting Bar"); 
    } 
    public void foo(){ 
     log("Entering Foo"); 
     executing = true; 
      try{ 
      // do something over the network 
      }catch(Exception e){ 
       // probably network down. Lets not worry about it 
      } 
     DelegateBar barPtr = new DelegateBar(Bar); 
     // Update UI .. call on form : form is a control 
     this.BeginInvoke(barPtr, new object[] {"someInfo", 3, false, null}); 
     log("Exiting Fool"); 
    } 

    public void callMeEveryFiveSeconds(){ 
     if(!executing) foo(); 
    } 

    private delegate void DelegateCallMe(); 

    // execute every 5 seconds. 
    private void timer1_Tick(object sender, EventArgs e) 
    { 
     Delegate del = new DelegateCallMe(callMeEveryFiveSeconds); 
     // appoligies if syntax is not right, it to convey the idea that callMeEveryFiveSeconds is called on the main thread (asynchronously) 
     this.beginInvoke(del, new object[]{}); 
    } 
} 
+0

为什么Bar的签名与Delaget不一样酒吧?这些应该匹配 – JMcCarty 2011-06-07 19:50:02

+0

哦..这是一个错字。我编辑了这篇文章。 – karephul 2011-06-07 20:07:07

+0

你确定Form在调用BeginInvoke之前已经完全加载了吗? http://social.msdn.microsoft.com/forums/en-US/winforms/thread/f58fe141-8908-430f-a2d4-2b2755d028cd/ – Christian 2011-06-07 20:22:02

该代码看起来对我来说很好,因为发布。如果不使用你的代码匹配,那么我会建议寻找下列之一:

1)如果你的耗时的任务,需要更长的时间,则FiveSeconds方法给予的没有被调用每一个

时间外观2)如果消费任务和更新UI的组合导致每次没有被调用方法的外观

3)如果消费任务中未显示的任何代码可以改变执行的值(或退出该方法,因为它可以设置为false)

+0

感谢您的回应,根据日志我相信BeginInvoke()不执行委托。我之前使用Invoke时,用户更常抱怨UI挂起。但即使使用BeginInvoke后,用户界面挂起的同一用户,但方式少频繁..我注意到,在“执行”标志为真的日志.. – karephul 2011-06-07 21:36:28