C# 创建后台计时器以异步运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15879476/
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
Creating a background timer to run asynchronously
提问by Mike Baxter
I'm really struggling with this. I'm creating a winforms
application in visual studio and need a background timer that ticks once every half hour - the purpose of this is to pull down updates from a server.
我真的很挣扎。我正在winforms
Visual Studio 中创建一个应用程序,需要一个每半小时滴答一次的后台计时器 - 这样做的目的是从服务器拉下更新。
I have tried a couple of different approaches but they have failed, either due to poor tutorial/examples, or to my own shortcomings in C#
. I think it would be a waste of time to show you what I have tried so far as it seems what I tried was pretty far off the mark.
我尝试了几种不同的方法,但它们都失败了,要么是由于教程/示例不佳,要么是我自己在C#
. 我认为向您展示我所尝试的内容是浪费时间,因为我尝试的内容似乎离目标很远。
Does anyone know of a clear and simple way of implementing an asynchronous background timer that is easily understandable by a C#
newbie?
有谁知道实现一个C#
新手很容易理解的异步后台计时器的清晰而简单的方法吗?
采纳答案by Mitch Wheat
// Create a 30 min timer
timer = new System.Timers.Timer(1800000);
// Hook up the Elapsed event for the timer.
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
...
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// do stuff
}
with the usual caveats of: timer won't be hugely accurate and might need to GC.KeepAlive(timer)
与通常的警告:计时器不会非常准确,可能需要 GC.KeepAlive(timer)
See also: Why does a System.Timers.Timer survive GC but not System.Threading.Timer?
另请参阅:为什么 System.Timers.Timer 在 GC 中存活,而 System.Threading.Timer 不能存活?
回答by JSJ
I think you need to know about all timer classes. See Jon's answer below.
我认为您需要了解所有计时器课程。请参阅下面乔恩的回答。
What kind of timer are you using?
- System.Windows.Forms.Timer will execute in the UI thread
- System.Timers.Timer executes in a thread-pool thread unless you specify a SynchronizingObject
- System.Threading.Timer executes its callback in a thread-pool thread
In all cases, the timer itself will be asynchronous - it won't "take up" a thread until it fires.
你用的是什么定时器?
- System.Windows.Forms.Timer 将在 UI 线程中执行
- System.Timers.Timer 在线程池线程中执行,除非您指定 SynchronizingObject
- System.Threading.Timer 在线程池线程中执行其回调
在所有情况下,计时器本身都是异步的——它不会“占用”一个线程,直到它被触发。
回答by the_virt
Declare member variable in your form:
在表单中声明成员变量:
System.Timers.Timer theTimer;
On form load (or whatever other time you need to start update polling), do:
在表单加载时(或任何其他需要开始更新轮询的时间),请执行以下操作:
theTimer = new System.Timers.Timer(1800000);
theTimer.Elapsed += PollUpdates;
theTimer.Start();
Declare your PollUpdates member function like this:
像这样声明你的 PollUpdates 成员函数:
private void PollUpdates(object sender, EventArgs e)
{
}