【问题标题】:control.invoke with an out parameter带有 out 参数的 control.invoke
【发布时间】:2017-06-11 19:33:44
【问题描述】:

Winforms、C#、VS2010。

我有一个在我的应用程序生命周期内运行的轮询线程。

有时它会在我的主窗体上调用一个事件。多年来我没有接触过代码,它运行成功,但现在我需要在参数列表中添加一个“out”参数。我在网上搜索过,但我发现的所有线程都与反射有关,并且尝试转换为我的上下文很复杂。我的不使用反射。

有人可以帮忙解决这个问题吗?在我读到的反射线程上,人们似乎检查了一些对象数组的输出参数结果,我没有在我的代码中使用它,而且我也不知道从哪里得到它。

private bool OnNeedUpdateCreateEvent(string title, string message,
  bool creatingNew, out string newPlanName)
{
    newPlanName = "";

    // 1st pass through this function. 
    // Check to see if this is being called from another thread rather 
    // than the main thread. If so then invoke is required
    if (InvokeRequired)
    {
      // Invoke and recall this method.
      return (bool)Invoke(new onNeedToUpdatePlanEvent(OnNeedUpdateCreateEvent),
        title, message, creatingNew, out newPlanName); <- wrong out param

    }
    else
    {
      // 2nd pass through this function due to invoke, or invoke not required
      return InputDlg(this, title, message, creatingNew, out newPlanName);
    }

} 

【问题讨论】:

    标签: c# multithreading winforms controls invoke


    【解决方案1】:

    这很像您已经知道的,只是您还没有找到数组。它由编译器自动创建。 Invoke method的签名是:

    public object Invoke(
        Delegate method,
        params object[] args
    )
    

    params 关键字让编译器自动创建数组。不错的语法糖,但在这里对您没有帮助。你只需要自己做,像这样:

    if (!creatingNew) {
        // Invoke and recall this method.
        object[] args = new object[] { title, message, creatingNew, null };
        var retval = (bool)Invoke(new onNeedToUpdatePlanEvent(OnNeedUpdateCreateEvent), args);
        newPlanName = (string)args[3];
        return retval;
    }
    // etc..
    

    【讨论】:

      猜你喜欢
      • 2018-05-11
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 2018-01-25
      • 2012-06-09
      • 2013-11-02
      • 1970-01-01
      相关资源
      最近更新 更多