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

编程入门 行业动态 更新时间:2024-10-28 13:13:16
本文介绍了从其他线程调用主线程中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 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 的滴答事件上,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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-28 18:30:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/736937.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   主线   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!