C#定时器VS在服务线程 [英] C# Timer vs Thread in Service

查看:401
本文介绍了C#定时器VS在服务线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有击中一个数据库,每10秒,并获取数据,如果有任何一个服务。问题是,处理这些数据可能需要长达30秒。如果我使用一个计时器10秒间隔,服务将获得相同的数据的两倍。



影响我正尝试实现(只是用于可视化):

 ,而(真)
{
如果(Getnrofrows()0)
做的东西
,否则
睡眠,持续10秒
}

PPL说了Thread.Sleep是生产性服务业是一个坏主意,我怎么做这个用的定时器<? / p>

/麦克风


解决方案

你有没有尝试设置定时器属性自动复位为false,并再次启用定时器,当刷新数据的过程就结束了。

 使用系统; 

公共类PortChat
{
公共静态System.Timers.Timer _timer;
公共静态无效的主要()
{

_timer =新System.Timers.Timer();
_timer.AutoReset = FALSE;
_timer.Interval = 100;
_timer.Elapsed + =新System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = TRUE;
Console.ReadKey();
}

静态无效_timer_Elapsed(对象发件人,System.Timers.ElapsedEventArgs E)
{
//做数据库刷新
_timer.Enabled = TRUE ;
}
}


I have a Service that hits a database every 10 sec and gets the data if there is any. The thing is that processing this data can take up to 30 sec. If I use a Timer with 10 sec interval the service will get the same data twice.

The effect i´m trying to achieve(Just for visualization):

while(true)
{
    if(Getnrofrows() > 0)
      do stuff
    else
      sleep for 10 sec
}

Ppl saying Thread.Sleep is a bad idea in production services, how do I do this with timers?

/mike

解决方案

Did you try to set Timer property auto reset to false, and enabling timer again when process of refreshing data is over

using System;

public class PortChat
{
    public static System.Timers.Timer _timer;
    public static void Main()
    {

        _timer = new System.Timers.Timer();
        _timer.AutoReset = false;
        _timer.Interval = 100;
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
        _timer.Enabled = true;
        Console.ReadKey();
    }

    static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        //Do database refresh
        _timer.Enabled = true;
    }
}

这篇关于C#定时器VS在服务线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆