简体   繁体   中英

How do I create a Timer in C#?

How do I create a Timer?

For my project I have to create a Timer, which is counting down, but

Task.Delay();
System.Threating.Threat.Sleep();

is not working, because it stops the whole application and I need it to stay responsive, for my timer to visually decrease. The Timer seems to also not to work, because when I use the Example from Jignesh Thakker , then I get an error, that the namespace "Forms" is not present.

The Timer Code

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();

t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();

void timer_Tick(object sender, EventArgs e)
{
    //Call method
}

Use a DispatcherTimer:

using System.Windows.Threading;
...

var t = new DispatcherTimer();

t.Interval = TimeSpan.FromSeconds(15);
t.Tick += timer_Tick;
t.Start();

void timer_Tick(object sender, EventArgs e)
{
}

There is over a half dozen Timer classes in .NET. Some are for specific Environments (like WebDevelopment). And most are different in where the counting is done (UI or Worker Thread) and thus if they have "Metronome Quality" and where the Tick event is raised (UI Thread or worker thread) and thus if you ahve to deal with Invocation and if their processing can be delayed by a busy UI Thread.

System.Windows.Forms.Timer is specificall Designed for Windows Forms and one of the Simpler ones. As the name implies, it is part of hte Windows Forms related .DLL's and namespaces. As you work with WPF, you do not have those avalible by default (but can add them).

The primary Timer for WPF is the Dispatcher Timer, wich works pretty similar to the WindowsForms one (counting and Tick Raise on UI thread). See Clemens Answer or the example for it.

Task.Delay and Thread.Sleep are not timers per say. They deal with adding a Delay to a Multitasking or Multithreading approaches Respectively. But if you do not ahve Multitasking or -Threading, you only end up stoppin your main thread. What Gusman wrote is adding Multitasking to the whole thing. Multitasking however is a tricky area you might not yet be ready for. While they are very important to learn, tehy are not beginners topics. You should propably stay at timers for now.

If you use System.Timers.Timer , then here's an example

System.Timers.Timer t = new System.Timers.Timer();
t.Elapsed += new ElapsedEventHandler(Work);
t.Interval = 10;
t.Enabled = true;

private void Work(object sender, ElapsedEventArgs e)
{
    //[Thread safety]
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.BeginInvoke((ElapsedEventHandler)Work, sender, e);
        return;
    }

    Task task = Task.Run(() =>
    {
        // Your non UI work

        Dispatcher.BeginInvoke((Action)delegate ()
        {
            // Your UI work
        });
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM