我通常使用以下技术来与控制台应用程序或服务运行相同的应用程序:
public static class Program{ #region Nested classes to support running as service public const string ServiceName = "MyService"; public class Service : Servicebase { public Service() { ServiceName = Program.ServiceName; } protected override void onStart(string[] args) { Program.Start(args); } protected override void onStop() { Program.Stop(); } } #endregion static void Main(string[] args) { if (!Environment.UserInteractive) // running as service using (var service = new Service()) Servicebase.Run(service); else { // running as console app Start(args); Console.WriteLine("Press any key to stop..."); Console.ReadKey(true); Stop(); } } private static void Start(string[] args) { // onstart pre here } private static void Stop() { // onstop pre here }}Environment.UserInteractive通常对于控制台应用为true,对于服务为false。从技术上讲,可以在用户交互模式下运行服务,因此您可以改为检查命令行开关。



