C# Console Application with Asynchronous Looping that listens to Console input

I’ve recently needed to write a Console Application to do some occasional monitoring.

The logic needed to live in a constantly running Game Loop yet the Console needed to be responsive to user input.

If quit (q) was called, the task needs to complete before the application ends.

.NET 4.0’s System.Threading.Tasks helped achieve this.

I based my code off this Stack Overflow post.

Here’s the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;

namespace NotifierBot
{
    class Program
    {
        static bool _running;
        static Bot _bot;

        static void Main()
        {
            _bot = new Bot();
            _bot.Start();

            _running = true;

            while (_running)
            {
                // check for user input
                checkInput(Console.ReadKey().KeyChar);
            }

            // wait for the task to finish before exiting
            _bot._task.Wait(); 
        }


        static void checkInput(char input)
        {
            if (input == 'q')
            {
                Console.WriteLine("\nQuit called from main thread");

                _bot.Stop();
                _running = false;
            }
        }
    }

    public class Bot
    {
        // we use Task.Factory to start a gameloop on a different thread. this allows the console to listen to user input events like 'q' 
        // as per
        // http://stackoverflow.com/questions/4576982/are-there-best-practices-for-implementing-an-asynchronous-game-engine-loop        

        CancellationTokenSource _cts;
        public Task _task;

        public void Start()
        {
            Console.WriteLine("\tBot Started");

            if (_cts == null)
            {
                _cts = new CancellationTokenSource();
                
                
                _task = Task.Factory.StartNew(() => Loop(_cts.Token), _cts.Token);
            }
        }

        private void Loop(CancellationToken token)
        {
            // The core loop
            Console.WriteLine("\tLoop started");


            while (!token.IsCancellationRequested)
            {
                Console.WriteLine("\tLoop!");

                token.ThrowIfCancellationRequested();
                Thread.Sleep(2000);
                Console.WriteLine("\t\tdo stuff");
            }

            Console.WriteLine("\tLoop ending");            
        }

        public void Stop()
        {
            Console.WriteLine("\tStop called");

            if (_cts != null)
            {
                _cts.Cancel();
                _cts = null;
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s