C# .NET 定时器异步运行吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/729137/
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
Do .NET Timers Run Asynchronously?
提问by MrEdmundo
I have a messaging aspect of my application using Jabber-net(an XMPP library.)
我有一个使用Jabber-net(一个XMPP 库)的应用程序的消息传递方面。
What I would like to do, if for some reason the connection to the Server is ended, is keep trying to connect every minute or so.
我想做的是,如果由于某种原因与服务器的连接终止,则每分钟左右继续尝试连接。
If I start a Timer to wait for a period of time before the next attempt, does that timer run asynchronously and the resulting Tick event join the main thread, or would I need to start my own thread and start the timer from within there?
如果我启动一个计时器以在下一次尝试之前等待一段时间,该计时器是否异步运行并且生成的 Tick 事件加入主线程,或者我是否需要启动我自己的线程并从那里启动计时器?
采纳答案by Jon Skeet
What kind of timer are you using?
你用的是什么定时器?
System.Windows.Forms.Timer
will execute in the UI threadSystem.Timers.Timer
executes in a thread-pool thread unless you specify aSynchronizingObject
System.Threading.Timer
executes its callback in a thread-pool thread
System.Windows.Forms.Timer
将在 UI 线程中执行System.Timers.Timer
在线程池线程中执行,除非您指定SynchronizingObject
System.Threading.Timer
在线程池线程中执行其回调
In all cases, the timer itself will be asynchronous - it won't "take up" a thread until it fires.
在所有情况下,计时器本身都是异步的——它不会“占用”一个线程,直到它被触发。
回答by cjk
The timer will effectively run in the background and cause events in your main thread to be executed.
计时器将有效地在后台运行并导致主线程中的事件被执行。
回答by Davy Landman
I'm not sure how the Timers in .NET are implemented, but if they use the windows API for creating a timer the form message loop receives a WM_TIMER
message and only when the form thread is not busy can it proces that request, so the timer would fire at the right time, but you could be stalling the UI thread. The timer would be started with the SetTimer
API and the OS will make sure to post a WM_TIMER
message.
我不确定 .NET 中的计时器是如何实现的,但是如果它们使用 Windows API 创建计时器,则表单消息循环会收到一条WM_TIMER
消息,并且只有当表单线程不忙时,它才能处理该请求,因此计时器会在正确的时间触发,但您可能会拖延 UI 线程。计时器将通过SetTimer
API启动,操作系统将确保发布WM_TIMER
消息。
I've checked, only System.Windows.Forms.Timer+TimerNativeWindow.StartTimer(Int32)
depends on:
我检查过,只System.Windows.Forms.Timer+TimerNativeWindow.StartTimer(Int32)
取决于:
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern IntPtr SetTimer(HandleRef hWnd, int nIDEvent, int uElapse, IntPtr lpTimerFunc);
So only this timer has the described "problem".
所以只有这个计时器有描述的“问题”。