从其他线程调用主线程中的方法

从其他线程调用主线程中的方法

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

问题描述

我正在尝试在 C# 应用程序中同时运行 3 个级别的计时器例如:

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

T1 将在应用程序的开头运行,然后在其 Tick 事件中,T2 将启动然后在 T2 的滴答事件上,T3 将启动.最后,在T3的tick事件上,应该在应用程序的主线程中做一些事情

T1 will run in the beginning of the application, then on its Tick event, T2 will startand 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");

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

08-20 06:02