简单的系统正常运行时间 [英] Simple System Uptime counter

查看:106
本文介绍了简单的系统正常运行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的正常运行时间应用程序存在一些轻微问题。这是代码的最大份额。用于保持持续更新的计时器。



I''m having some slight problems with my uptime app. This is the lion''s share of the code. A timer for the purpose of keeping it continuous updated.

TimeSpan ts = TimeSpan.FromMilliseconds(Environment.TickCount);

public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Enabled = true;
    timer1.Interval = 1000;
    timer1.Start();
}



但是,加载应用程序时。仅显示当前正常运行时间 - 直到应用程序启动时 - 。我不太明白为什么它不计数。


However, when the application is loaded. Only the current uptime - up to the time the application was started - is shown. I don''t quite see why it doesn''t keeps counting.

private void timer1_Tick(object sender, EventArgs e)
{
    uptimeTxt.Text = ts.Days + "d" + ts.Hours + "h" +
                     ts.Minutes + "m" + ts.Seconds + "s";
}

推荐答案

ts 的值设置一次,这就是为什么你的正常运行时间永远不会增加。你总是一遍又一遍地显示完全相同的值。



你需要设置 ts的值(或获取Environment.TickCount的值)在Timer Tick事件处理程序中。
The value of ts is set once, which is why your uptime never increments. You''re constantly showing the exact same value over and over again.

You need to set the value of ts (or get the value of Environment.TickCount) in the Timer Tick event handler.


就此代码块而言,您可能会收到错误:

As far as in this block of code you might get an error:
private void timer1_Tick(object sender, EventArgs e)
        {
            uptimeTxt.Text = ts.Days + "d" + ts.Hours + "h" +
                             ts.Minutes + "m" + ts.Seconds + "s";
        }





因为您尝试从特定线程更新upimeTxt文本值。这不是一个UI线程。

所以基本上,你必须在UI同步代码中执行uptimeTxt.Text更新工作流程:





Because you try to update upimeTxt text value from a particular thread . which is not a UI thread.
So basically , you must perform uptimeTxt.Text update workflow in UI synchronized code:

if(uptimeTxt.InvokeRequired){
this.Invoke((MethodInvoker)delegate {
    someLabel.Text = newText; // runs on UI thread
}
})


这篇关于简单的系统正常运行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆