简体   繁体   中英

C# Windows Service doesn't run

I wrote my first C# Windows Service: Now I have a little Issue. If I Debug the code like that

public static void Main(string[] args)
{
    if (Environment.UserInteractive)
    {
        m_thread = new Thread(execute);
        m_thread.Start();
    }
    else
    {
    }
}

The Code works quite well.

But If I install and run the Service, nothing happens. I start the service with the OnStart method (See below)

protected override void OnStart(string[] args)
{
    m_thread = new Thread(execute);
    m_thread.IsBackground = true;
    m_thread.Start();
    base.OnStart(args);
}

The execute method will create some sub tasks like enter a Value in a DB

public static void execute()
{
    var cancellationSource = new CancellationTokenSource();
    CancellationToken token = cancellationSource.Token;
    Console.WriteLine("RUN");
    var t1 = Task.Run(() => WriteData("test", "test", token));
}

As I said in the beginning of this post, When I ran this in "Debug Mode" everything works, and the values are entered in the DB. But if I install & run it, the values will not be entered in the DB.

Can anyone explain me why or what I forgot?

I don't know what happened to your project, but services don't get started by the magic service fairy. You actually have to do that. At some point in time, your Main method looked like this:

ServiceBase[] ServicesToRun = new ServiceBase[] { new MyService(args) };
ServiceBase.Run(ServicesToRun);

That code got lost. Put it back, preferably in your empty else block.

What I discovered when creating my own services, was that the Main thread does not get blocked when ran as a service or as User Interactive. If the main thread exits- then it terminates the application. Remember - it is still a console application - if the Main thread (static void main() ) exits - then the application effectively reaches the end of its life.

I solved it easily by adding a Console.ReadLine(); to prevent the application ever reaching the end of the Start method.

Alternatives include looping - and then using the Stop method to provide a means to break out of the infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM