【问题标题】:Should Windows services be built as Windows Application or Console Application?Windows 服务应该构建为 Windows 应用程序还是控制台应用程序?
【发布时间】:2016-09-28 15:52:17
【问题描述】:

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

鉴于我已决定使用服务,它应该构建为 Windows 应用程序还是控制台应用程序?

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

我怀疑这两种方法最终都会起作用,但是为了满足我的编码强迫症,是否有合理的技术理由来选择其中一种(例如避免启动不必要的 conhost.exe 进程或其他东西)?

FWIW,我使用的是 C#/.NET 4.0。

【问题讨论】:

  • 您可以在“添加新项目”窗口中使用 Windows 服务模板。
  • “Windows 应用程序”是什么意思?一个 WinForms 项目?在 Windows 上运行的任何项目都是“Windows 应用程序”,包括“控制台应用程序”。
  • @gunr2171 在 PE 标头中有一个标志,表明可执行映像是 GUI 应用程序还是控制台应用程序(查看 IMAGE_OPTIONAL_HEADER.Subsystem
  • “Windows 应用程序”是 Visual Studio 自己的描述,如项目属性的“应用程序”选项卡上右侧的“输出类型:”下所示。大多数人只是说“winforms”作为这个的简写。
  • @amonroejj,好吧。我以为您在谈论项目类型“Windows 应用程序”。

标签: c# .net winforms visual-studio console-application


【解决方案1】:

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

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

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

为此,您可以使用 Windows 窗体应用程序模板创建项目。 然后添加对System.ServiceProcess 程序集的引用。此外,您不需要参考中的 System.Windows.FormsSystem.Drawing 之类的程序集。然后使用 Add New Item 窗口,添加一个新的 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

【讨论】:

  • 我不认为我们在同一波长上。我的问题不是“如何做到这一点”的问题。这是一个“两个选项中的哪一个,更重要的是,为什么”的问题。
  • 至少由于Windows Service Template的输出类型是Windows Application,所以以Windows Application作为起点是可以接受的。我没有说不要使用控制台应用程序模板,但看到输出类型足以让我使用 Windows 应用程序。
  • 例如,如果您通过创建控制台应用程序来启动它,您将在执行时看到一个控制台窗口。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多