You are perfectly right. First thing to note is: the difficulty you pointed out is a good evidence of the fact that your requirement makes little to no practical sense and should not be imposed for any real-life task. Also, the formulation of the question is inaccurate: in programming, even if you use some parallel computing supported by hardware, nothing is really "simultaneous".
At the same time, just for giggles, (or, if you will, for study/learning purposes), I can show how to resolve this problem. Just to simplify it, let's assume that you need just two operations: input and output of a line. Here is how:
class InterlockedConsole {
object lockObject = new object();
void WriteLine(string value) { lock (lockObject) { System.Console.WriteLine(value); } }
string ReadLine(string value) { lock (lockObject) { return System.Console.ReadLine(); } }
}
One practical note: in .NET discussions, people often question: why not using
lock(this) {/* ... */}
? The answer is: yes, it will work perfectly, but does not provide fool-proof quality of the approach shown above. It will really work the same way, until someone (foolishly :-)) tries to use the same instance to lock something else, which can have unexpected side effects, including deadlocks. Private access to the
lockObject
helps to avoid such troubles.
That's all. To understand how it works in multithreading situation, learn about locking and/or mutual exclusion:
http://en.wikipedia.org/wiki/Mutual_exclusion[
^],
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx[
^].
[EDIT]
In response to the discussion in the comments to this answer, I have some practical advice on using console-only application even if this application is a multithreading one, with several threads using the same console. The idea is: everything will work well with one console, but you need to exclude just one thing: interactive input.
There are many really good console-only applications which have a number of benefits over UI application. One of such benefits is that you can avoid a lot of manual work associated with UI applications, all those multiple clicks in different items, because you can use the console-only applications in a batch file, and combine it with other applications of this sort, even bind together their inputs and outputs.
All such good application uses one simple model: output is done to console, but all input is performed via the command line parameters. Interactive input, inherently inconvenient and unreliable, is never used.
In case some parts of input are too big to be suitable as a parameter, the following approach is used: one or more of the parameters are file names, so the user should provide data in some file(s).
I have a very easy-to-use library for command line parsing parsing and command invocation available in my CodeProject article
Enumeration-based Command Line Utility[
^].
One more library is recommended in the text of my article.
—SA