计时器已用事件不会在Windows服务c#vs2013中触发

时间:2014-07-18 17:54:01

标签: c#

我的计时器已用完事件在我的Windows服务中没有触发,为什么?我在论坛中搜索,但解决方案对我没有任何帮助。

在program.cs的主要部分:

static class program
{
    static void Main()
    {
        #if DEBUG
            servicioCR cr = new servicioCR();
            cr.beginProcess();
        #else
        #endif


        //ServiceBase[] ServicesToRun;
        //ServicesToRun = new ServiceBase[] 
        //{ 
        //    new servicioCR() 
        //};
        //ServiceBase.Run(ServicesToRun);
    }

}

在我的服务类

    public static System.Timers.Timer timer;

    public servicioCR()
    {
        timer = new System.Timers.Timer(5000);
        timer.AutoReset = false;

        timer.Elapsed += timer_Elapsed;

        InitializeComponent();
    }

已过去的事件

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        try
        {
            timer.Stop();

            //Do stuff
        }
        catch (System.Exception ex)
        {
            EventLog.WriteEntry(ex.Message);
        }
        finally
        {
            timer.Start();
        }
    }

和beginProcess()

    internal void beginProcess()
    {
        timer.Start();
    }

我正在使用.NET Framework 4.5和VS 2013 ...我不明白为什么它不起作用,我从另一个工作正常的解决方案中复制了这个。

如果我在经过事件的事件的一行中放置一个断点,它就永远不会中断。

为什么呢?感谢

1 个答案:

答案 0 :(得分:1)

您的计时器正在运行,但程序在计时器启动之前自行关闭。你需要暂停某种类型的暂停,这样你的程序就不会自行关闭。

static void Main()
{
    #if DEBUG
        servicioCR cr = new servicioCR();
        cr.beginProcess();
        Console.WriteLine("Program Running");
        Console.ReadLine();
    #else
    #endif


    //ServiceBase[] ServicesToRun;
    //ServicesToRun = new ServiceBase[] 
    //{ 
    //    new servicioCR() 
    //};
    //ServiceBase.Run(ServicesToRun);
}

以下是来自我的一个旧项目的代码片段,这使您可以将程序作为服务和控制台应用程序运行。在Visual Studio中,只需将调试器设置为在安装项目屏幕中传递参数--console

class Program
{
    public static void Main(string[] args)
    {
        var example = new MyExampleApp();
        if (args.Contains("--console"))
        {
            example.ConsoleRun(args);
        }
        else
        {
            ServiceBase.Run(example);
        }
    }
}

class MyExampleApp : ServiceBase
{

    public void ConsoleRun(string[] args)
    {
        Console.WriteLine(string.Format("{0}::starting...", GetType().FullName));

        OnStart(args);

        Console.WriteLine(string.Format("{0}::ready (ENTER to exit)", GetType().FullName));
        Console.ReadLine();

        OnStop();

        Console.WriteLine(string.Format("{0}::stopped", GetType().FullName));
    }

    //... the rest of the code from your service class.
}
相关问题