如何在C#写的WINDOWS服务中,使线程在固定的时间运行

如题所述

第1个回答  2016-07-19
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;

namespace TickService
{
    public partial class Service1 : ServiceBase
    {
        Timer timer1;

        public Service1()
        {
            InitializeComponent();
            timer1 = new Timer();
            //Set the interval of timer to 3 seconds.
            timer1.Interval = 3000;
            //Enable the timer.
            timer1.Enabled = true;
            timer1.Elapsed+=new ElapsedEventHandler(timer1_Elapsed);
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            
            //Append the text to the sample file.
            StreamWriter writer = File.AppendText(@"C:\sample.txt");
            writer.WriteLine("Start");
            writer.Close();
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            //Append the text Stop to the C:\sample.txt file.
            StreamWriter writer = File.AppendText(@"C:\sample.txt");
            writer.WriteLine("Stop");
            writer.Close();
        }

        private void timer1_Elapsed(object sender, EventArgs e)
        {
            //Set the enable property to false.
            //timer1.Enabled = false;
            //Append the text Tick to the C:\sample.txt file.
            StreamWriter writer = File.AppendText(@"C:\sample.txt");
            writer.WriteLine("Tick");
            writer.Close();
            //timer1.Enabled = true;
        }
    }
}

本回答被网友采纳
相似回答