C# 从其他线程调用主线程中的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17123061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling methods in main thread from other threads
提问by user2302005
I am trying to run 3 levels of timers at the same time in a C# application for example:
我正在尝试在 C# 应用程序中同时运行 3 个级别的计时器,例如:
T1 will run in the beginning of the application, then on its Tick event, T2 will start and then on the tick event of T2, T3 will start. Finally, on the tick event of T3, something should be done in the main thread of the application
T1 将在应用程序的开头运行,然后在其 Tick 事件上,T2 将启动,然后在 T2 的滴答事件上,T3 将启动。最后,在T3的tick事件上,应该在应用程序的主线程中做一些事情
My problem seems to be that the code in the main thread is not working when it is being called by an other thread
我的问题似乎是主线程中的代码在被其他线程调用时不起作用
What should I do to let the main thread run its functions by a call from other threads?
我应该怎么做才能让主线程通过来自其他线程的调用来运行它的功能?
采纳答案by VladL
Most probably the problem is that your main thread requires invocation. If you would run your program in debugger, you should see the Cross-thread operation exception, but at run time this exception check is disabled.
最有可能的问题是您的主线程需要调用。如果您将在调试器中运行您的程序,您应该会看到跨线程操作异常,但在运行时此异常检查被禁用。
If your main thread is a form, you can handle it with this short code:
如果你的主线程是一个表单,你可以用这个短代码处理它:
if (InvokeRequired)
{
this.Invoke(new Action(() => MyFunction()));
return;
}
or .NET 2.0
或 .NET 2.0
this.Invoke((MethodInvoker) delegate {MyFunction();});
EDIT: for console application you can try following:
编辑:对于控制台应用程序,您可以尝试以下操作:
var mydelegate = new Action<object>(delegate(object param)
{
Console.WriteLine(param.ToString());
});
mydelegate.Invoke("test");

