C# Console Application - Keep it running

前端 未结 11 1712
萌比男神i
萌比男神i 2020-12-16 01:02

I am about to develop a console application that will be required to continually run and carry out work at specific times.

My question is what is are best methods or

相关标签:
11条回答
  • 2020-12-16 01:32

    Create a Task and then Wait it.

    class Program
    {
        static void Main(string[] args)
        {
            var processTask = Process();
            processTask.Wait();
        }
    
        private static async Task Process()
        {
            var isNotCancelled = true;
    
            while (isNotCancelled)
            {
                //Polling time here
                await Task.Delay(1000);
    
                //TODO: Do work here and listen for cancel
                Console.WriteLine("I did  some work...");
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-16 01:34

    Well I'm sure at some point it should stop, no?

    Spawn a thread that does work, and have the main thread block on Console.ReadLine() if you want it to be runnable as a console app too.

    If you really just want to pause the main thread forever, just block on a ManualResetEvent you never fire.

    But, consider using a service if you can.

    0 讨论(0)
  • 2020-12-16 01:38

    While you should really be using a service for this, if you need/want to do this anyway, you can use a ManualResetEvent to do this:

    private ManualResetEvent Wait = new ManualResetEvent(false);
    

    When you're finished 'starting' and want to just wait, you'd then do:

    Wait.WaitOne();
    

    When you want to stop and let it exit, you can then do:

    Wait.Set();
    
    0 讨论(0)
  • 2020-12-16 01:39

    A better solution would be to write a console application that does its job and quits. You can then use the Windows Task Scheduler to run it periodically.

    0 讨论(0)
  • 2020-12-16 01:40

    You probably don't want to just spin in a loop needlessly consuming processor time.

    Assuming you are on windows, you should have a loop that never ends with a call to WaitForSingleObject() or WaitForMultipleObjects() or MsgWaitForMultipleObjects() depending on your needs. Then have some synchronization object that wakes you up, such as a named event.

    See the Win32 Synchronization documentation here. If you elaborate more on what your program needs to do, we can probably provide more specific advice.

    0 讨论(0)
  • 2020-12-16 01:41

    Sending a thread to sleep: System.Threading.Thread.Sleep(10000);

    Waiting for a key to be pressed: Console.WriteLine("Press any key to continue..."); Console.Read();

    0 讨论(0)
提交回复
热议问题