开发者

How to read/write on console at the same time using threads

I want to implemente a C# Console Application that runs a simulation. Also, I want to give to the user the oportunity to acelerate/decelerate the speed of the simulation pressing '+' or '-' on console.

Is there a way to read the console while writing on it? I believe I could use multithreading for this, but I don't how to do it (I'm still new on开发者_StackOverflow C#).

Thank you very much!


You can check Console.KeyAvailable prior to calling Console.ReadKey(). This will let you check the console to see if there is input waiting (ie: the user pressed + or -) without blocking. If you just don't try to read if there is no input available, your main thread will never block waiting on the user.

Using this mechanism, you can actually do this in a single threaded application.


Yes, there is a way to read/write at the "same time". There are a couple of ways to do it:

Use another Thread:

First, you start a thread that is responsible for writing to the console.

Thread t = new Thread(()=>{RunSimulation();});
t.IsBackground = true;
t.Start();

The simulation method would look something along the lines of:

public void RunSimulation()
{
    while(running)
    {
        // Puts the thread to sleep depending on the run speed
        Thread.Sleep(delayTime);
        Console.WriteLine("Write your output to console!");
    }
}

Second, you can continually let the main thread poll for user input in order to make adjustments.

string input = string.Empty;

while(input.Equals("x", StringComparison.CurrentCultureIgnoreCase)
{
    input = Console.ReadKey();
    switch(input)
    {
    case "+":
        // speeds up the simulation by decreasing the delayTime
        IncreaseSpeed();
        break;
    case "-":
        // slows down the simulation by decreasing the delayTime
        DecreaseSpeed();
        break;
    default:
        break;
    }
}

Use a Timer:

Another approach is to use a [Timer][1] and adjust the frequency of callbacks on the timer instead of adjusting the sleep time on a thread:

// Create the timer
System.Timers.Timer aTimer = new System.Timers.Timer(10000);

// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnPrintSimulationResult);

// Change the Interval to change the speed of the simulation
aTimer.Interval = 2000; // <-- Allows you to control the speed of the simulation
aTimer.Enabled = true;

Of course, you have to deal with thread safety, but this should give you a decent place to start. You can come back once you try one of those approaches and you're having a specific problem with it, I'm sure people would be happy to address any particular issues you have. Note that it will not be a very graceful-looking solution to do it in the console, but it will work. If you want something more graceful, then simply make a GUI application that has a text area, redirect the console output to the text area and add 2 buttons (+/-) to adjust the speed. [1]: http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜