从其他线程主线程中调用方法 [英] Calling methods in main thread from other threads

查看:103
本文介绍了从其他线程主线程中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C#应用程序
为例同时运行3个级别的定时器:

I am trying to run 3 levels of timers at the same time in a C# application for example:

T1会的开始运行应用程序,然后在其Tick事件,T2将启动
,然后在T2的Tick事件,T3将启动。
最后,在T3的Tick事件,事情应该在应用程序

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

我的问题似乎是主线程完成在主代码线程不工作时,它是由一个其他线程

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?

推荐答案

最有可能的问题是,你的主线程需要调用。如果你想在调试器中运行您的程序,你应该看到跨线程操作异常,但在运行时,此异常检查功能。

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;
 }

或.NET 2.0

this.Invoke((MethodInvoker) delegate {MyFunction();});



编辑:控制台应用程序,您可以尝试以下操作:

for console application you can try following:

  var mydelegate = new Action<object>(delegate(object param)
  {
    Console.WriteLine(param.ToString());
  });
  mydelegate.Invoke("test");

这篇关于从其他线程主线程中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆