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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Good idea! I haven't thought of multithreading. But can you show me how to do multithreading in C#?
edited my answer. The second link provides an example how to implement a worker class, which you can use for your GameLogic
Thank you so much! That perfectly solved my problem! The website does not allow me to accept your answer now. I will do it a bit later.
I'm glad i was able to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.