Cze*_*cat 5 c# controls multithreading invoke winforms
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);
}
}
Run Code Online (Sandbox Code Playgroud)
就像您已经知道的一样,您只是还没有找到该数组。它是由编译器自动创建的。Invoke 方法的签名是:
public object Invoke(
Delegate method,
params object[] args
)
Run Code Online (Sandbox Code Playgroud)
它是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..
Run Code Online (Sandbox Code Playgroud)