简体   繁体   English

如何在C#中创建计时器?

[英]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. 计时器似乎也不起作用,因为当我使用Jignesh Thakker的Example时 ,出现一个错误,即名称空间“ Forms”不存在。

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: 使用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. .NET中有超过六种Timer类。 Some are for specific Environments (like WebDevelopment). 有些是针对特定环境的(例如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. 而且大多数区别在于完成计数的地方(UI或工作线程),是否具有“ Metronome质量”以及引发Tick事件的地方(UI线程或工作线程)以及是否要处理调用以及繁忙的UI线程可能会延迟其处理。

System.Windows.Forms.Timer is specificall Designed for Windows Forms and one of the Simpler ones. System.Windows.Forms.Timer是专门为Windows窗体和更简单的窗体之一设计的。 As the name implies, it is part of hte Windows Forms related .DLL's and namespaces. 顾名思义,它是Windows窗体相关的.DLL和名称空间的一部分。 As you work with WPF, you do not have those avalible by default (but can add them). 使用WPF时,默认情况下没有可用的对象(但可以添加它们)。

The primary Timer for WPF is the Dispatcher Timer, wich works pretty similar to the WindowsForms one (counting and Tick Raise on UI thread). WPF的主要计时器是分派器计时器,其工作原理与WindowsForms非常相似(UI线程上的计数和滴答作响)。 See Clemens Answer or the example for it. 请参阅Clemens答案或其示例。

Task.Delay and Thread.Sleep are not timers per say. 每次说Task.Delay和Thread.Sleep都不是计时器。 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. 但是,如果您不使用多任务处理或-Threading处理,则只会停止主线程。 What Gusman wrote is adding Multitasking to the whole thing. 古斯曼(Gusman)写的是在整个过程中增加多任务处理。 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 ,那么这是一个示例

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
        });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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