chezy525
chezy525

Reputation: 4174

C#: programmatically enter text for console.readline

Ok, I know this is bad program design, and I'll probably get around to fixing it later, but I'm looking for a quick fix...

I have a C# program that starts a thread that does some work, then in the main thread it starts listening for user input to manually kill the worker. The pseudo-code looks like this:

WorkerClass worker = new WorkerClass();
worker.Start(); //function that starts a new worker thread.

while(!Console.ReadLine().ToUpper().Equals("STOP")){}

worker.Join(); //function that cleanly stops the worker thread.

This works just fine, and originally the worker would always just hang out and continually do stuff, so it made sense to just wait for me to type "stop". However, I've since modified the worker thread so that it eventually reaches the end of it's tasks, and it knows it. Since there's nothing else happening, I'd like the main thread to stop too, but it's still waiting for input from the console. So, is there anyway I can enter text from the worker thread that's read as console input in the main thread?

I do want to keep the ability to manually stop the worker cleanly, so just changing the while statement to check for the worker completion instead of console input isn't really an option.

Upvotes: 1

Views: 1339

Answers (1)

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

Rather than doing that, why not have your worker register an event, once the event is raised, you can then kill your loop and exit the application.

Upvotes: 4

Related Questions