【问题标题】:Try catch with a delegate尝试与代表接洽
【发布时间】:2014-06-21 18:25:08
【问题描述】:

我作为以前的 c++ 编码员在 c# 中输入其他人的代码库。在他的代码中,我发现 sn-ps 看起来像这样:

MethodInvoker invoker = new MethodInvoker
      (delegate()
      {
        ...
      }
      );
try
{
   this.Invoke(invoker);
}
catch (Exception x)
{
  ...
}

我的问题是:是否有任何理由使用 delegate 然后 try-catch?第三到第五行花括号内的代码可以不只是放在try catch中吗?是否有一些我还不知道的 c# 细微差别?

【问题讨论】:

    标签: c# delegates try-catch


    【解决方案1】:

    这不只是调用委托,而是将它传递给一个名为 Invoke 的方法。

    这更像是您使用的 UI 框架/环境的细微差别。例如,在 WinForms 中,只有一个 GUI 线程可以改变 UI 控件的状态。如果要从其他线程更改控件的状态,则需要调用 Invoke 方法并传递委托,就像在您的示例中一样。调用 Invoke 基本上意味着“在 GUI 线程上运行这个委托”。

    看到这些问题:How to update the GUI from another thread in C#? Invoke in Windows Forms

    和 Control.Invoke 文档: http://msdn.microsoft.com/en-us/library/a1hetckb.aspx

    【讨论】:

      【解决方案2】:

      您在这里所做的是defining a simple anonymous method,稍后将在winform's Control thread 上调用它

      MethodInvoker invoker = new MethodInvoker
            (delegate()
            {
              ...
            }
            );
      

      接下来要做的是the execution的匿名方法

      try
      {
         this.Invoke(invoker);
      }
      catch (Exception x)
      {
        ...
      }
      

      Can the code inside the curly braces on the third to fifth lines not just be placed inside that try catch?

      是的,你可以这样做 (MethodInvoker)

      try
          {
             this.Invoke((MethodInvoker)delegate()
            {
             //
            }
            ));
          }
          catch (Exception x)
          {
            ...
          }
      

      【讨论】:

        猜你喜欢
        • 2017-12-26
        • 2019-02-15
        • 2019-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-26
        • 2021-05-02
        • 1970-01-01
        相关资源
        最近更新 更多