• C# Windows Service


    1.创建Windows服务

    这时候点击“启动”按钮,会提示我们启动失败。

    这因为Windows服务不能像普通窗口程序那样启动,接下来就安装服务。

    2.配置

    在Service1.cs上右键,选择“查看设计器”,

    然后再在上面的空白处,右键选择“添加安装程序”,

    这时候,Visual Studio就会自动为我们生成一个ProjectInstaller.cs文件,接下来,右键ProjectInstaller.cs,选择“查看设计器”,就可以看到如下的界面,

    可以看到两个控件,点击右击第一个控件,打开属性设计器,将其中的Account设置为LocalSystem(本地服务),

    接下来,右击上面的第二个控件,打开属性界面,设置ServiceName,和将其中的StratType设置为Automatic,

    测试代码:

    1,

        public partial class Service1 : ServiceBase
        {
            private readonly Timer _MyTimer;
            public Service1()
            {
                InitializeComponent();
                _MyTimer = new Timer(10*1000); //10秒钟启动一次
                _MyTimer.Elapsed += _MyTimerElapsed;
            }
    
            protected override void OnStart(string[] args)
            {
                _MyTimer.Start();
            }
    
            protected override void OnStop()
            {
                _MyTimer.Stop();
            }
            internal void _MyTimerElapsed(object sender, ElapsedEventArgs e)
            {
                WriteLog("开始执行了");
            }
    
    
            public void WriteLog(string msg)
            {
                string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                try
                {
                    using (StreamWriter sw = File.AppendText(logPath))
                    {
                        sw.WriteLine("消息:" + msg);
                        sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        sw.WriteLine("**************************************************");
                        sw.WriteLine();
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                }
                catch (IOException e)
                {
                    using (StreamWriter sw = File.AppendText(logPath))
                    {
                        sw.WriteLine("异常:" + e.Message);
                        sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
                        sw.WriteLine("**************************************************");
                        sw.WriteLine();
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                }
            }
    
        }

    2,

        public partial class Service1 : ServiceBase
        {
            System.Threading.Timer timer;
            public Service1()
            {
                InitializeComponent();
                InitTimer();
            }
    
            protected override void OnStart(string[] args)
            {
            }
    
            protected override void OnStop()
            {
            }
    
    
            public void InitTimer()
            {
                TimerCallback callback = new TimerCallback(_MyTimerElapsed);
                AutoResetEvent eventobj = new AutoResetEvent(false);
                timer = new System.Threading.Timer(callback, eventobj, 0, 10* 1000);//执行回调间隔
            }
    
    
            private void _MyTimerElapsed(object sender)
            {
                WriteLog("开始执行了lalala");
            }
    
    
            public void WriteLog(string msg)
            {
                string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                try
                {
                    using (StreamWriter sw = File.AppendText(logPath))
                    {
                        sw.WriteLine("消息:" + msg);
                        sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        sw.WriteLine("**************************************************");
                        sw.WriteLine();
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                }
                catch (IOException e)
                {
                    using (StreamWriter sw = File.AppendText(logPath))
                    {
                        sw.WriteLine("异常:" + e.Message);
                        sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
                        sw.WriteLine("**************************************************");
                        sw.WriteLine();
                        sw.Flush();
                        sw.Close();
                        sw.Dispose();
                    }
                }
            }
    
        }

    上面的代码,笔者写到Service1.cs类中,该类是Visual Sudio在启动的时候,自动为我们创建好的类文件。观察这个类文件,可以发现,该类继承了ServiceBase,ServiceBase是服务类的基类,也就是说想要创建服务,必需继承这个类,ServiceBase中有两个方法比较常用,分别为OnStart()和OnStop(),顾名思义,OnStart方法在服务启动的时候调用,OnStop方法在服务停止的时候调用。

    3.安装Windows服务

    安装方法一:

    CMD  管理员运行

    1:安装windows服务

    cd C:WindowsMicrosoft.NETFrameworkv4.0.30319
    2:安装windows服务
    installUtil.exe J:测试项目WindowsService1WindowsService1inDebugWindowsService1.exe
    3:启动windows服务  
    net start SyncSupplierService

    4:卸载windows服务
      InstallUtil.exe /u J:测试项目WindowsService1WindowsService1inDebugWindowsService1.exe

    服务安装好后,就可以启动服务了。

    按下“Win+R”打开运行界面框,然后输入services.msc,进入到服务界面,找到自己对应的服务,启动。

    安装方法二:Install.bat

    cd /d %~dp0

    set installutilpath=%windir%Microsoft.NETFrameworkv4.0.30319installutil.exe

    echo %installutilpath%

    cd %~dp0

    %installutilpath% J:测试项目WindowsService1WindowsService1inDebugWindowsService1.exe

    pause

    卸载:Uninstall.bat

    cd /d %~dp0
    
    set installutilpath=%windir%Microsoft.NETFrameworkv4.0.30319installutil.exe
    
    echo %installutilpath%
    
    cd %~dp0
    
    %installutilpath% -u J:测试项目WindowsService1WindowsService1inDebugWindowsService1.exe
    
    pause

    在上面的OnStart方法中,我们打印了日志。

    作者:chenze
    出处:https://www.cnblogs.com/chenze-Index/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    如果文中有什么错误,欢迎指出。以免更多的人被误导。
  • 相关阅读:
    Word2010如何从指定页设置页码
    十大常见web漏洞及防范
    CSRF攻击与防御
    信息安全常见漏洞类型汇总
    回忆一次校招笔试的题目
    Python操作rabbitmq系列(三):多个接收端消费消息
    Python操作rabbitmq系列(二):多个接收端消费消息
    Python操作rabbitmq系列(一)
    Python操作Redis
    Python连接Redis
  • 原文地址:https://www.cnblogs.com/chenze-Index/p/11377737.html
Copyright © 2020-2023  润新知