簡體   English   中英

C#:如何讓時鍾正常工作?

[英]C#: How can I make the clock work correctly?

我正在使用 Visual Studio 2022 開發一個名為 Charms Bar Port的新存儲庫 GitHub,它要求 UI 在左下方顯示時鍾和日期,如此圖所示。

但是,無論是否存在,時鍾似乎都不會更新:

  • 后台工作者
  • 定時器

有沒有一個很好的方法可以在一個循環中持續跟蹤時間?

使用來自外部來源的后台工作人員和/或計時器的一些代碼從未起作用。 例如:即使時間是“9:00”,“8:34”也會卡在屏幕上。

    Timer t = new Timer();
    private void Form1_Load(object sender, EventArgs e)
    {
        // Normally, the timer is declared at the class level, so that it stays in scope as long as it
        // is needed. If the timer is declared in a long-running method, KeepAlive must be used to prevent
        // the JIT compiler from allowing aggressive garbage collection to occur before the method ends.
        // You can experiment with this by commenting out the class-level declaration and uncommenting
        // the declaration below; then uncomment the GC.KeepAlive(aTimer) at the end of the method.
        //System.Timers.Timer aTimer;

        // Create a timer and set a two second interval.
        t = new System.Timers.Timer();
        t.Interval = 2000;

        // Create a timer with a two second interval.
        //t = new System.Timers.Timer(2000);

        // Hook up the Elapsed event for the timer.
        t.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        t.AutoReset = true;

        // Start the timer
        t.Enabled = true;

        // If the timer is declared in a long-running method, use KeepAlive to prevent garbage collection
        // from occurring before the method ends.
        GC.KeepAlive(t);

    }

    //timer eventhandler
    private void OnTimedEvent(object sender, EventArgs e)
    {
        //update label
            Date.Content = DateTime.Today.ToString("MMMM d");
            Week.Content = DateTime.Today.ToString("dddd");
            Clocks.Content = DateTime.Now.ToString("hh:mm");
        t.Enabled = true;
    }
}

您應該使用調度程序從不同的線程更新 UI。

你的代碼應該是:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        _initTimer();
    }
    
    private Timer t = null;
    private readonly Dispatcher dispatcher = Dispatcher.CurrentDispatcher;

    private void _initTimer()
    {
        t = new System.Timers.Timer();
        t.Interval = 1000;
        t.Elapsed += OnTimedEvent;
        t.AutoReset = true;
        t.Enabled = true;
        t.Start();
    }

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        dispatcher.BeginInvoke((Action)(() =>
        {
            DateTime today = DateTime.Now;                      
            Clocks.Content = today.ToString("hh:mm:ss");
            // do additional things with captured 'today' variable.
        }));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM