C# 如何从不同的线程获取布尔值?
要执行跨线程操作,我使用以下命令:C# 如何从不同的线程获取布尔值?,c#,multithreading,winforms,invoke,C#,Multithreading,Winforms,Invoke,要执行跨线程操作,我使用以下命令: this.Invoke(新的MethodInvoker(()=>myMethod()); 但是,例如,我不能做到以下几点: this.Invoke(new MethodInvoker(() => bool myBool = getBool()); return myBool; 我该怎么做?我不能只做bool myBool=getBool(); 因为我得到了一个跨线程操作错误 提前谢谢。不知道你的意思 但你可以这样做 bool myBool = fal
this.Invoke(新的MethodInvoker(()=>myMethod());
但是,例如,我不能做到以下几点:
this.Invoke(new MethodInvoker(() => bool myBool = getBool());
return myBool;
我该怎么做?我不能只做bool myBool=getBool();因为我得到了一个跨线程操作错误 提前谢谢。不知道你的意思 但你可以这样做
bool myBool = false;
this.Invoke(new MethodInvoker(() => myBool = getBool()));
return myBool;
如果我错了,请让我明白试试这个:
delegate T MyDelegate<out T>();
public bool MethodName()
{
bool b = (bool)this.Invoke(new MyDelegate<bool>(() => getBool()));
return b;
}
delegate T MyDelegate();
公共bool MethodName()
{
bool b=(bool)this.Invoke(newmydelegate(()=>getBool());
返回b;
}
事实上,问题是,我想在if语句中使用它:if(this.Invoke(new MethodInvoker(()=>!myBool)){
…但这不起作用。我会仅仅通过方法名来调用它吗?@Adam:你到底是什么意思?现在你可以直接调用MethodName()< /代码>以获取BooL,但您可以用您想要的名称替换<代码>方法名>代码。考虑使用基于任务的异步,而不是管理您自己的线程。基于任务的异步,您只需<代码>等待< /Cord>任务的值;<代码>任务<代码>将返回BoOL值并在线程APPR上恢复执行。符合上下文的。