Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6874917
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T04:15:18+00:00 2026-05-27T04:15:18+00:00

I have a process that runs in it’s own thread and can be started/stopped

  • 0

I have a process that runs in it’s own thread and can be started/stopped without blocking. This will eventually go into a Windows service, but I am setting this up in a console app for now until it is fully fleshed out.

After the call to Start(), I want the main program thread to block until Ctrl-C is pressed. I know that this will work:

public static void Main(string[] args)
{
    bool keepGoing = true;

    var service = new Service();

    System.Console.TreatControlCAsInput = false;

    System.Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
    {
        e.Cancel = true;
        service.Stop();
        keepGoing = false; // Break the while loop below
    };

    service.Start();

    while( keepGoing )
    {
        Thread.Sleep(100); // 100 is arbitrary
    }

}

However, I find the flag and arbitrary sleep value bothersome. I know that the CPU cost is practically 0 in the while loop, but I’d rather have a “hard” block that releases as soon as the Ctrl-C handler is done. I devised the below, using a semaphore to block until the anonymous Ctrl-C handler is done:

public static void Main(string[] args)
{
    var service = new Service();

    var s = new Semaphore(1, 1);

    System.Console.TreatControlCAsInput = false;

    System.Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
    {
        e.Cancel = true;
        service.Stop();
        s.Release(); // This will allow the program to conclude below
    };

    service.Start();

    s.WaitOne(); // This will not block
    s.WaitOne(); // This will block w/o CPU usage until the sempahore is released

}

Is this a bad design? Is it overkill? Is it dangerous?

EDIT:

I also hook up AppDomain.CurrentDomain.UnhandledException as follows:

AppDomain.CurrentDomain.UnhandledException += delegate {
  service.Stop();
  s.Release();
};

EDIT the 2nd:

I should note that it is crucial that the Stop() method get called on exit. @Adam Ralph has a perfectly good pattern for a hybrid console/service, but didn’t have this information when answering the Q.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T04:15:18+00:00Added an answer on May 27, 2026 at 4:15 am

    We have a similar requirement in a few of our apps. They are Windows services, but for debugging we often want to run them as console apps. Moreover, we usually code new apps as Windows services fairly early on but often don’t want to have to actually run them as a service until later, once we’ve proved the concept, etc.

    This is the pattern we use:-

    using (var service = new Service())
    {
        if (Environment.UserInterActive)
        {
            service.Start();
            Thread.Sleep(Timeout.Infinite);
        }
        else
        {
            ServiceBase.Run(service);
        }
    }
    

    Telling the thread to sleep infinitely might seem inefficient, but this is only for debugging scenarios and the redundant thread costs no CPU time, just some memory (about 1MB), which is mostly composed of the stack space allocated to the thread. The process can still be exited with Ctrl+C or by closing the command window.

    — EDIT —

    If you find that service.Dispose() is not being called when Ctrl+C is pressed (i.e. a rude abort happens) and the call to Dispose() is crucial, then I guess you could explicitly do this like so:-

    using (var service = new Service())
    {
        if (Environment.UserInterActive)
        {
            Console.CancelKeyPress += (sender, e) => service.Dispose();
            service.Start();
            Thread.Sleep(Timeout.Infinite);
        }
        else
        {
            ServiceBase.Run(service);
        }
    }
    

    Note that Stop() should be encapsulated in Dispose().

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple application that runs a process that can last for several
I have a Java process that runs in the background. How can I quickly
I have a process that runs in a thread (used as a realtime signal
I have a process that currently runs in a Delphi application that I wrote
I have a build process that does the following: Runs TLBIMP on a number
I have a .CAB file that runs as part of an installer process on
I have android application and service that runs in separate process. Application and service
When you have a piece of software that runs an out of process COM
I have a process that runs on cron every five minutes. Usually, it takes
We have a process that runs a few times a day (via a Windows

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.