110,566
社区成员
发帖
与我相关
我的任务
分享
private void main(object sender, EventArgs e)
{
Thread thread_1s=new Thread(new ThreadStart(UI_callback));
thread_1s.IsBackground=true;
thread_1s.Start();
}
private void UI_callback()
{
while(true)
{
this.BeginInvoke(new EventHandler(RefreshUI),null);
Thread.Sleep(1000);
}
private void RefreshUI(object sender, EventArgs e)
{
toolStripStatusLabelTime.Text=DateTime.Now.Tostring();
//根据当前数据刷新界面,例如if(alarms[Station.Id].Count>0){pictureBox1.Image=imageList1.Images[3];}
}
Thread thread_1s=new Thread(new ThreadStart(UI_callback));
thread_1s.IsBackground=true;
thread_1s.Start();
}
private void UI_callback()
{
while(true)
{
this.BeginInvoke(new EventHandler(RefreshUI),null);
Thread.Sleep(1000);
}
这里,你弄一个线程在那里“玩儿cpu”,让它循环着(本身线程上下文相关数据结构要占用资源,它还抢占其它线程的CPU调度资源),目的是干什么呢?只是为了向主线程注册一个 RefreshUI 方法么?并且你的 RefreshUI 方法也还都是在主线程排队执行的。
.net的Timer比你自己写的线程死循环要高效得多得多。就算是你使用最低级的Timer(.net至少共有3种或者4种Timer),使用它的代码比你写的线程代码更清晰。你的这种程序根本用不着什么线程的。就像刚学编程的人一样学会拖一个Timer控件到设计画面上,就比你的代码还要好。
public partial class Form1 : Form
{
public Form1()
{
FlowLayoutPanel panel = new FlowLayoutPanel() { Padding = new Padding(8), Dock = DockStyle.Fill };
for (int i = 0; i < 40; i++)
{
myUserControlList.Add(new MyUserControl());
panel.Controls.AddRange(myUserControlList.ToArray());
}
this.Controls.Add(panel);
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
foreach (MyUserControl myControl in myUserControlList)
{
MyData data = new MyData() { Description = DateTime.Now.Second.ToString(), Status = random.Next(3) };
myControl.Update(data);
}
}
Random random = new Random();
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer() { Interval = 1000 };
List<MyUserControl> myUserControlList = new List<MyUserControl>();
class MyData
{
public string Description { get; set; }
public int Status { get; set; }
}
class MyUserControl : UserControl
{
public MyUserControl()
{
this.Controls.AddRange(new Control[] { label, pictureBox });
this.Size = new Size(60, 30);
}
public void Update(MyData data)
{
label.Text = data.Description;
pictureBox.Image = images[data.Status % images.Length];
}
Label label = new Label() { Width = 30 };
PictureBox pictureBox = new PictureBox() { Location = new Point(30, 0), };
static Image[] images = new Image[] { SystemIcons.Warning.ToBitmap(), SystemIcons.Question.ToBitmap(), SystemIcons.Information.ToBitmap() };
}
}
var t = new System.Timers.Timer(1000);
t.Enabled = true;
t.Elapsed += (o, e) =>
{
ThreadPool.QueueUserWorkItem(new WaitCallback(update), null);
};
void update(object s)
{
this.BeginInvoke(new action(()=>{
///UI
}));
}