Integrating Service Code into a .NET Console Application
How can you transform a console application into a Windows service without adding a separate project?
Solution:
You can seamlessly integrate service code into your console application to allow it to run as both a console app and a service. Consider the following technique:
using System.ServiceProcess; public static class Program { 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(); } } 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 code here } private static void Stop() { // OnStop code here } }
Explanation:
The above is the detailed content of How Can I Integrate Service Code Directly into a .NET Console Application?. For more information, please follow other related articles on the PHP Chinese website!