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

时间:2016-09-28 15:52:17

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

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

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

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

我怀疑其中任何一个实际上都会工作,但为了满足我的编码器OCD,是否有一个合理的技术原理为一个或另一个(例如避免旋转不必要的conhost.exe进程或其他东西)?

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

1 个答案:

答案 0 :(得分:1)

您可以在“添加新项目”窗口中使用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