C# 中是否有一个不在 Windows.Forms 命名空间中的计时器类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/169332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 16:30:38  来源:igfitidea点击:

Is there a timer class in C# that isn't in the Windows.Forms namespace?

c#.netschedulingtimer

提问by MrDatabase

I want to use a timer in my simple .NETapplication written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console application.

我想在我用 C# 编写的简单.NET应用程序中使用计时器。我能找到的唯一一个是 Windows.Forms.Timer 类。我不想只为我的控制台应用程序引用这个命名空间。

Is there a C# timer (or timer like) class for use in console applications?

是否有用于控制台应用程序的 C# 计时器(或类似计时器)类?

采纳答案by albertein

回答by Eric Schoonover

I would recommend the Timerclass in the System.Timersnamespace. Also of interest, the Timerclass in the System.Threadingnamespace.

我会推荐命名空间中的TimerSystem.Timers。同样有趣的Timer是,System.Threading命名空间中的类。

using System;
using System.Timers;

public class Timer1
{
    private static Timer aTimer = new System.Timers.Timer(10000);

    public static void Main()
    {
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();
    }

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}

Example from MSDN docs.

MSDN 文档中的示例。

回答by DaveK

System.Diagnostics.Stopwatchif your goal is to time how long something takes to run

System.Diagnostics.Stopwatch如果您的目标是计算运行所需的时间

回答by Sucharit

It is recommended to not to use System.Timer's Timer class.

建议不要使用System.Timer的 Timer 类。

回答by theburningmonk

There are at least the System.Timers.Timerand System.Threading.Timerclasses that I'm aware of.

至少有我知道的System.Timers.TimerSystem.Threading.Timer类。

One thing to watch out though (if you haven't done this before already), say if you already have the System.Threading namespace in your using clause already but you actually want to use the timer in System.Timers you need to do this:

但是需要注意的一件事(如果您之前还没有这样做过),假设您的 using 子句中已经有 System.Threading 命名空间,但您实际上想在 System.Timers 中使用计时器,您需要这样做:

using System.Threading;
using Timer = System.Timers.Timer;

Jon Skeet has an article just on Timers in his multithreading guide, it's well worth a read: http://www.yoda.arachsys.com/csharp/threads/timers.shtml

Jon Skeet 在他的多线程指南中有一篇关于定时器的文章,非常值得一读:http: //www.yoda.arachsys.com/csharp/threads/timers.shtml

回答by Stéphane Gourichon

This question is old and existing answers cover well the issue as it was at the time. In the meantime, something new has happened.

这个问题很旧,现有的答案很好地涵盖了当时的问题。与此同时,新的事情发生了。

Timer, sure, for what ?

计时器,当然,为了什么?

Using a timer is a way to run some processing with some delay and/or at regular interval. There are two cases:

使用计时器是一种以一定的延迟和/或定期间隔运行某些处理的方法。有两种情况:

(1) it's just to run some short code periodically without any thread concern, no trouble, no mess. If the plain Windows Forms timer is not suitable, then System.Timers.Timerwith its SynchronizingObjectproperty makes it more straightforward than System.Threading.Timer.

(1) 只是定期运行一些短代码,没有任何线程问题,没有麻烦,没有混乱。如果普通的 Windows 窗体计时器不适合,那么System.Timers.Timer它的SynchronizingObject属性使它比System.Threading.Timer.

(2) what you're coding is in the realm of asynchronous concurrent processing. That has traditionally been error-prone, difficult to debug, to get right, whatever the plain timer used.

(2) 您正在编码的是异步并发处理领域。无论使用什么普通计时器,这在传统上都是容易出错、难以调试、难以正确处理的。

In case 2 you might get away with traditional approach, but beware, complexity is lurking and ready to eat you not just once but any time you just don't make the best choice, with cumulative effects.

在第 2 种情况下,您可能会使用传统方法逃脱惩罚,但要注意,复杂性潜伏着,并且随时准备吃掉您,而不仅仅是一次,而是在您没有做出最佳选择的任何时候,都会产生累积效应。

Now we've got something better

现在我们有了更好的东西

If your situation deals with some kind of "event" handling (whatever the way it's coded: keypresses, mouse buttons, bytes from a serial port, from a network connection, from measurements, etc), you should consider Reactive Programming.

如果您的情况涉及某种“事件”处理(无论其编码方式如何:按键、鼠标按钮、来自串行端口的字节、来自网络连接、来自测量等),您应该考虑响应式编程。

Reactive Programming has in recent years somehow uncovered how to code for these situations, while not falling into complexity traps.

近年来,响应式编程以某种方式揭示了如何针对这些情况进行编码,同时又不会陷入复杂性陷阱。

So, technically the following link is an answer to the question: it is a timer which is in the System.Reactive.Linqnamespace: Observable.Timer Method (System.Reactive.Linq)

因此,从技术上讲,以下链接是该问题的答案:它是一个位于System.Reactive.Linq命名空间中的计时器:Observable.Timer Method (System.Reactive.Linq)

To be fair, it's a timer that comes and plays well with the Reactive Programming mindset and a lot of game-changing stuff. Yet it might or might not be the best tool, depending on the context.

公平地说,它是一个计时器,它与响应式编程思维方式和许多改变游戏规则的东西很好地结合在一起。然而,它可能是也可能不是最好的工具,这取决于上下文。

Since this question is .NET-centric, you might be interested in Good introduction to the .NET Reactive Framework

由于此问题以 .NET 为中心,因此您可能对 .NET Reactive Framework 的良好介绍感兴趣

Or for a clear, illustrated, more general (not Microsoft-centric) document, this seems good The introduction to Reactive Programming you've been missing.

或者对于一个清晰的、有插图的、更通用的(不是以 Microsoft 为中心的)文档,这看起来不错The Introduction to Reactive Programming you've been missing