相关疑难解决方法(0)

C#为什么定时器频率极度偏离?

这两个System.Timers.TimerSystem.Threading.Timer火在离请求的那些相当不同的时间间隔.例如:

new System.Timers.Timer(1000d / 20);
Run Code Online (Sandbox Code Playgroud)

产生一个每秒发射16次而不是20次的计时器.

为了确保太长的事件处理程序没有副作用,我写了这个小测试程序:

int[] frequencies = { 5, 10, 15, 20, 30, 50, 75, 100, 200, 500 };

// Test System.Timers.Timer
foreach (int frequency in frequencies)
{
    int count = 0;

    // Initialize timer
    System.Timers.Timer timer = new System.Timers.Timer(1000d / frequency);
    timer.Elapsed += delegate { Interlocked.Increment(ref count); };

    // Count for 10 seconds
    DateTime start = DateTime.Now;
    timer.Enabled = true;
    while (DateTime.Now < start + TimeSpan.FromSeconds(10))
        Thread.Sleep(10);
    timer.Enabled = false;

    // Calculate …
Run Code Online (Sandbox Code Playgroud)

c# timer frequency deviation

14
推荐指数
3
解决办法
8269
查看次数

Windows服务在特定分钟内每小时运行一次

我需要帮助.我有Windows服务,我需要在特定时间每小时运行一次这项服务,例如:09:05,10:05,11:05,....我的服务现在每小时开始,但从我开始这项服务的每个小时开始.那么我怎样才能实现我的需求呢.

我的代码:

public partial class Service1 : ServiceBase
{
    System.Timers.Timer timer = new System.Timers.Timer();

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        this.WriteToFile("Starting Service {0}");

        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

        timer.Interval = 60000;

        timer.Enabled = true;
    }

    protected override void OnStop()
    {
        timer.Enabled = false;

        this.WriteToFile("Stopping Service {0}");
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        this.WriteToFile(" interval start {0}");
    } }
Run Code Online (Sandbox Code Playgroud)

c# windows-services timer

3
推荐指数
1
解决办法
4871
查看次数

标签 统计

c# ×2

timer ×2

deviation ×1

frequency ×1

windows-services ×1