gpt4 book ai didi

c# - Windows 服务应该构建为 Windows 应用程序还是控制台应用程序?

转载 作者:太空宇宙 更新时间:2023-11-03 12:39:05 26 4
gpt4 key购买 nike

这个问题不是关于是使用服务还是非服务(已经有几个 SO 问题涵盖了这个问题)。

如果我决定使用一项服务,它应该构建为 Windows 应用程序还是控制台应用程序?

我问是因为我用的是Visual Studio 2015服务项目模板(Visual C#/Windows/Classic Desktop/Windows Service)创建练习项目,默认是Windows Application。如果我试图事先预测它会选择什么,我就会错误地预测控制台应用程序。

我怀疑两者最终都可以正常工作,但为了满足我的编码强制症,是否有合理的技术理由支持其中一个(例如避免启动不必要的 conhost.exe 进程或其他)?

FWIW,我正在使用 C#/.NET 4.0。

最佳答案

您可以在“添加新项目”窗口中使用 Windows 服务模板。

如果出于任何原因(例如使用 Visual Studio Express 版本)您想使用不同的模板创建它,您可以使用 Windows 窗体应用程序模板。

如果您查看 Windows 服务项目的属性,您将看到:

enter image description here

为此,您可以使用 Windows 窗体应用程序模板创建项目。然后添加对 System.ServiceProcess 程序集的引用。此外,您在引用中不需要像 System.Windows.FormsSystem.Drawing 这样的程序集。然后使用“添加新项”窗口,添加一个新的 Windows 服务并将 Program.cs 更改为:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace WindowsService1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}

有关更多信息,请查看 How to: Create Windows Services

关于c# - Windows 服务应该构建为 Windows 应用程序还是控制台应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39752263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com