已回答 需要将控制台应用程序作为服务运行

迪帕克

新成员
已加入
2021年2月12日
留言内容
3
编程经验
1-3
我有一个控制台应用程序,它每15分钟作为调度程序运行一次。这需要一直处于活动状态。但是我的VM正在重新引导,因此有时会关闭应用程序。

现在,我将代码复制到VM中,并运行应用程序的Release模式。是否可以将其转换为Windows服务,以便即使VM随时重新启动,应用程序也可以自行启动。请帮助我的步骤。

谢谢
 
Solution
我认为最好的方法是创建一个可以作为控制台应用程序或Windows服务运行的项目。这样做的好处是,它使调试应用程序变得更加容易,因为调试Windows服务是很痛苦的。这是我创建的应用程序的重要组成部分,该应用程序目前在新南威尔士州政府的生产环境中运行。请注意,该项目是作为控制台应用程序创建的。
Program.cs:
using System.IO;
using System.Linq;
using System.ServiceProcess;
using SI.Moh.Phisco_Periph.Dto.Mapping;

namespace SI.Moh.Periph.Submissions.Service
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the...

金西尼

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
3,553
地点
悉尼,澳大利亚
编程经验
10+
我认为最好的方法是创建一个可以作为控制台应用程序或Windows服务运行的项目。这样做的好处是,它使调试应用程序变得更加容易,因为调试Windows服务是很痛苦的。这是我创建的应用程序的重要组成部分,该应用程序目前在新南威尔士州政府的生产环境中运行。请注意,该项目是作为控制台应用程序创建的。
Program.cs:
using System.IO;
using System.Linq;
using System.ServiceProcess;
using SI.Moh.Phisco_Periph.Dto.Mapping;

namespace SI.Moh.Periph.Submissions.Service
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            DomainMapper.MapDomain();

            if (args.Length == 1 && args[0] == "/console")
            {
                // Run the application as a Console app.
                using (var processor = new SubmissionProcessor())
                {
                    var folder = new DirectoryInfo(Properties.Settings.Default.SubmissionsRootFolder);

                    foreach (var file in folder.GetFiles(Properties.Settings.Default.SubmissionFileNamePattern).OrderBy(fi => fi.CreationTime))
                    {
                        processor.EnqueueFile(file.FullName);
                    }

                    processor.ProcessQueuedFiles();
                }
            }
            else
            {
                // Run the application as a Windows service.
                var servicesToRun = new ServiceBase[]
                {
                    new SubmissionService()
                };

                ServiceBase.Run(servicesToRun);
            }
        }
    }
}
If the argument /console is received on the commandline, the application will run as a regular Console app. I have that argument set on the 除错 项目属性的页面。否则,该应用程序将假定它已作为Windows服务安装。
SubmissionService:
using System;
using System.IO;
using System.ServiceProcess;
using ApplicationLogger = SI.Moh.Phisco_Periph.Global.ApplicationLogger;

namespace SI.Moh.Periph.Submissions.Service
{
    public partial class SubmissionService : ServiceBase
    {
        private const string ERROR_LOG_NAME = "PeriphErrorLog";
        private const string INFO_LOG_NAME = "PeriphInfoLog";

        private SubmissionProcessor processor;

        public SubmissionService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                processor = new SubmissionProcessor();

                var path = Properties.Settings.Default.SubmissionsRootFolder;
                var filter = Properties.Settings.Default.SubmissionFileNamePattern;

#if DEBUG
                ApplicationLogger.Inst.LogInfo(INFO_LOG_NAME, "Path: " + path);
                ApplicationLogger.Inst.LogInfo(INFO_LOG_NAME, "Filter: " + filter);
#endif

                // Process files already in the submission folder.
                foreach (var file in new DirectoryInfo(path).GetFiles(filter))
                {
                    processor.EnqueueFile(file.FullName);
                }

                processor.ProcessQueuedFilesAsync();

                // Watch for new files in the submission folder.
                submissionFolderWatcher.Path = path;
                submissionFolderWatcher.Filter = filter;
                submissionFolderWatcher.EnableRaisingEvents = true;
            }
            catch (Exception ex)
            {
                ApplicationLogger.Inst.LogException(ERROR_LOG_NAME, ex.Message, ex);
            }
        }

        protected override void OnStop()
        {
        }

        private void submissionFolderWatcher_Renamed(object sender, RenamedEventArgs e)
        {
            ApplicationLogger.Inst.LogInfo(INFO_LOG_NAME, "File detected: " + e.FullPath);

            processor.EnqueueFile(e.FullPath);
            processor.ProcessQueuedFilesAsync();
        }
    }
}
As you can see, the if block in the Main method loops through the files in a folder and adds them to a queue, then calls SubmissionProcessor.ProcessQueuedFiles. The else block creates a SubmissionService object and that does the same thing in its OnStart method, so when the application starts up as a Windows service, and also in the Renamed event handler of a FileSystemWatcher.
runasconsole.bat:
REM =----------------------------------------------------------=
REM Runs the PeriPH Submission Processor Service as a console app.
REM Please ensure you run this batch file as Administrator,
REM and that the PeriPH Submission Processor Service is NOT running.
REM =----------------------------------------------------------=
REM
C:
CD bin\Debug
SI.Moh.Periph.Submissions.Service.exe /console
PAUSE
install.bat:
REM =----------------------------------------------------------=
REM Installs the PeriPH Submission Processor Service.
REM Please ensure you run this batch file as Administrator.
REM =----------------------------------------------------------=
REM
C:
CD C:\PeriPH\Service
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" SI.Moh.Periph.Submissions.Service.exe
PAUSE
unistall.bat:
REM =----------------------------------------------------------=
REM Uninstalls the PeriPH Submission Processor Service.
REM Please ensure you run this batch file as Administrator.
REM =----------------------------------------------------------=
REM
C:
CD C:\PeriPH\Service
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe" /u SI.Moh.Periph.Submissions.Service.exe
PAUSE
 
解决方案
最佳 底部