问题描述
我正在使用Windows窗体应用程序,其中有几个所谓的服务",它们从Twitter,Facebook,Weather,Finance等各种服务中轮询数据.现在,我的每个服务都有其单独的轮询间隔设置,因此我想为每个服务实现一个 System.Windows.Forms.Timer
并设置其 Interval
属性因此,每个计时器将以预设的时间间隔触发一个事件,该事件将导致服务最好通过 BackgroundWorker
异步提取新数据.
I'm working on a windows forms app where I have several so called "services" that poll data from various services like Twitter, Facebook, Weather, Finance. Now each of my services has its individual polling interval setting so I was thinking I could implement a System.Windows.Forms.Timer
for each of my services and set its Interval
property accordingly so that each timer would fire an event at the preset interval that will cause the service to pull new data preferably async through a BackgroundWorker
.
这是最好的方法吗?否则会减慢我的应用程序的运行速度,从而导致性能问题.有更好的方法吗?
Is this the best way to do it? or will it slow down my app causing performance issues. Is there a better way of doing it?
谢谢!
推荐答案
您可以使用一个 Timer
来做到这一点,只需要更智能的间隔方法即可:
You can do it with one Timer
, just needs smarter approach to interval:
public partial class Form1 : Form
{
int facebookInterval = 5; //5 sec
int twitterInterval = 7; //7 sec
public Form1()
{
InitializeComponent();
Timer t = new Timer();
t.Interval = 1000; //1 sec
t.Tick += new EventHandler(t_Tick);
t.Start();
}
void t_Tick(object sender, EventArgs e)
{
facebookInterval--;
twitterInterval--;
if (facebookInterval == 0)
{
MessageBox.Show("Getting FB data");
facebookInterval = 5; //reset to base value
}
if (twitterInterval == 0)
{
MessageBox.Show("Getting Twitter data");
twitterInterval = 7; //reset to base value
}
}
}
这篇关于在C#中实现多个计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!