Andy Leo
Andy Leo

Reputation: 55

How to keep track of user input in C# console application?

I'm making a console game using C#. I want to my program to execute a block of code any time the user hits the arrow keys. Although that sounds pretty easy, I have no idea how to do that because I'm kind of new to C#.

PS I'm working on VS for mac.

EDIT 1: I want to keep track of user input means that I don't want it to stop other tasks when the program is listening for a user input.

Upvotes: 1

Views: 960

Answers (1)

Tobias Theel
Tobias Theel

Reputation: 3217

Your GameLogic should run in a separate thread in an endless loop. You can keep track by listening to Console.ReadKey() in an while(true) loop endless loop on your main Thread. Everytime a Key is pressed you could throw an Event which which is handled by your other Thread.

To start a new Thread have a look at: How do I run a simple bit of code in a new thread?

A clean aproach would be to create a GameLogicWorker which holds a private Thread(The cleanest aproach in my opinion) This answere shows how to do that: https://stackoverflow.com/a/8123600/4992212

But there are several options. You can also use async and await keywords to achieve async operations.

Upvotes: 1

Related Questions