1

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.

Andy Leo
  • 55
  • 1
  • 8

1 Answers1

1

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.

Tobias Theel
  • 3,088
  • 2
  • 25
  • 45