Mik*_*ter 22 c# asynchronous timer winforms
我真的很挣扎.我正在winforms
visual studio中创建一个应用程序,并且需要一个每半小时打一次的后台计时器 - 这样做的目的是从服务器下载更新.
我尝试了几种不同的方法,但是由于教程/示例不好或者我自己的缺点,它们都失败了C#
.我认为到目前为止,向我展示我所尝试过的东西将是浪费时间,因为我认为我的尝试远远不够.
有没有人知道一种清晰简单的方法来实现C#
新手很容易理解的异步后台计时器?
Mit*_*eat 33
// 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
}
Run Code Online (Sandbox Code Playgroud)
通常的警告:计时器不会非常准确,可能需要 GC.KeepAlive(timer)
另请参阅:为什么System.Timers.Timer能够在GC中存活但不能在System.Threading.Timer中存活?
the*_*irt 10
在表单中声明成员变量:
System.Timers.Timer theTimer;
Run Code Online (Sandbox Code Playgroud)
在表单加载(或您需要开始更新轮询的任何其他时间),执行:
theTimer = new System.Timers.Timer(1800000);
theTimer.Elapsed += PollUpdates;
theTimer.Start();
Run Code Online (Sandbox Code Playgroud)
声明你的PollUpdates成员函数如下:
private void PollUpdates(object sender, EventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)
我想你需要知道所有的计时器类.请参阅下面Jon的回答.
你用的是什么样的计时器?
- System.Windows.Forms.Timer将在UI线程中执行
- 除非指定SynchronizingObject,否则System.Timers.Timer将在线程池线程中执行
- System.Threading.Timer在线程池线程中执行其回调
在所有情况下,计时器本身都是异步的 - 在它发生之前它不会"占用"一个线程.
归档时间: |
|
查看次数: |
42770 次 |
最近记录: |