为什么不能从后台线程启动计时器? [英] Why isn't it possible to start a timer from a background thread?

查看:86
本文介绍了为什么不能从后台线程启动计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于backgroundworker.runworkerasync也是如此。



我遇到了这个问题并通过在BackgroundWorker.RunWorkerCompleted中启动计时器来解决它。因为它与主要线程在同一个线程上。



我尝试过的事情:



我成功如上所述,但不明白为什么会出现问题?

解决方案

简单:它是一个Control,这意味着它是一个UI组件(即使它不可见),它们只能在UI线程上访问。你可以 - 理论上 - 调用它来启动它(因为Invoke将代码移动到UI线程)但这可能会破坏BackgroundWorker的目的!


正如OriginalGriff所写,< a href =https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx> System.Windows.Forms.Timer 是UI组件。通常,您可以通过将其拖到表单上来获取它。

但你可以在代码中实现它,就像你对每个普通类一样。从你喜欢的任何线程。然后你可以从那个线程调用它。



但我宁愿建议将这些计时器保留在UI线程中,因为有其他设计用于其他thrads: System.Timers.Timer System.Threading.Timer



原因是,如果您最初使用Forms.Timer,因为定时器调用将在UI中执行某些操作,您将不再允许从其他定时器的回调函数执行此操作。相反,您必须添加一层调用。< br $> b $ b

从本质上讲,你必须决定使用invoke的位置:调用计时器(如果它在UI线程上)或者从计时器调用到UI线程。 / BLOCKQUOTE>

Same for backgroundworker.runworkerasync.

I had this problem and solved it by making the timer start in the BackgroundWorker.RunWorkerCompleted. because it's on the same thread as the main one.

What I have tried:

I succeeded as said above, but don't understand why the problem?

解决方案

Simple: it's a Control, which means it's a UI component (even if it isn't visible) and they can only ever be accessed on the UI thread. You could - in theory - Invoke it to start it (since Invoke moves the code to the UI thread) but that would probably defeat the purpose of the BackgroundWorker!


As OriginalGriff wrote, the System.Windows.Forms.Timer is a UI component. Usually you get it int your application by dragging one onto a Form.
But you can instatiate it in code like you would do with every ordinary class. From any thread you like. You can then call it from that thread.

But I'd rather advise to leave those timers in UI thread because there are alternavies designed to be used in other thrads: System.Timers.Timer and System.Threading.Timer.

Of cause, if you initially used Forms.Timer because the timer call will do something in the UI, you will no longer be allowed to do that from the other timers' callback functions. Instead, you will have to add a layer of invoking.

In essence, you will have to decide where to use invoke: Calls into the timer (if it is on UI thread) or out of the timer into UI thread.


这篇关于为什么不能从后台线程启动计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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