Jump to content
  • Advertisement
Sign in to follow this  
TigerSam

C# Console Window - Locking

This topic is 4254 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all, Is there a simple way to lock the c# console window so i can only write to it one at a time? At the minute i have a multithreaded c# sevrer and this is recieving packets and outputting them to the console. This is fine but when i want to create a packet my self i need to enter my message on screen first. This gets messy if half way thru writing my messgae the contents of another gets displayed too by another thread. Any ideas would hel. Cheers.

Share this post


Link to post
Share on other sites
Advertisement
You can use a mutex or monitor to block other threads while the current thread writes. I'd suggest wrapping System.Console in a thread-safe way: have a method to write to the console that blocks.

You can use System.Threading.Monitor to make sure only one thread can access an object at once. So if you have a shared object (of any type) that indicates permission to write to the console, you can get a lock on it, write to the console, and release your lock on it. Any other thread that tries to write during that time will first try to get a lock on the shared object, which won't happen until the first thread finishes writing and releases its lock.


public static void WriteLine(string s)
{
Monitor.Enter(someSharedObject);
Console.WriteLine(s);
Monitor.Exit(someSharedObject);
}


Note that Monitor or Mutexes are really important in almost any multithreaded program to make it safer to access data from multiple threads.

Share this post


Link to post
Share on other sites
public static void WriteLine(string s)
{
Monitor.Enter(someSharedObject);
Console.WriteLine(s);
Monitor.Exit(someSharedObject);
}


This is not quite optimal. What if Console.Writeline throws an exception? In general, you should use something like the following:

public static void WriteLine(string s)
{
lock (someSharedObject)
{
Console.WriteLine(s);
}
}


This is equivelant to:

public static void WriteLine(string s)
{
Monitor.Enter(someSharedObject);
try
{
Console.WriteLine(s);
}
finally
{
Monitor.Exit(someSharedObject);
}
}


As you can see, it's now safer on two counts: 1) you can't simply forget to release your lock on the object, 2) if an exception occurs, then the lock will still be released.

Share this post


Link to post
Share on other sites
Hi thanks for the replys

I dont know if ive mis interpretted your way of thinking but what im wanting to do is: i have say 5 threads A B C D and E. Thread A waits for an input from myself whilst B-E get inputs over the network. When A gets an input i want to lock the remaining threads from writing to the console, until A has finished. then the other threads can operate as per usual.

Share this post


Link to post
Share on other sites
Here's some demonstration source (uncompiled and untested I'm afraid, but it should theoretically work)

using System;
using System.Threading;

namespace ThreadingExample
{
public class ThreadedWrite
{
[MTAThread]
public static void Main(string[] args)
{
/* Here I just use other functions, but bear in mind it takes a
* delegate as a parameter, so you can actually use an anonymous
* method as appropriate.
*/

Thread A = new Thread(getInput);
A.Start();

Thread[] BCDE = new Thread[4];
foreach (Thread t in BCDE)
{
t = new Thread(lookBusy);
t.Start();
}
}

void getInput()
{
/* I just lock on the current instance of the class, here. Your
* (proper) design probably calls for a specific object to lock
* on for the console.
*/

lock (this) // Acquire lock
{
Console.WriteLine("Please enter some character:");
char someCharacter = Console.Read(); // Blocks
Console.WriteLine("Thank you for " + someCharacter);
} // Release lock
}

void lookBusy()
{
lock (this)
for (int i = 0; i < 5; ++i)
Console.WriteLine(i.ToString());
}
}
}






Expected output:

Please enter some character:
[User inputs 'A']
Thank you for A
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4


EDIT: Fixed lang attribute of source box
EDIT2: Really fixed attribute
EDIT3: It's worth mentioning that the object you're locking on must, if I recall, be an instance of a reference type as a boxing operation will not be performed on a value type.
EDIT4: Or are you looking for something like:

[Information being received over network, threads B - E handle and print]
[You interrupt to send your own packet - threads B - E continue to handle the messages they receive and queue them for printing]
[You've sent your packet - threads B - E now print their queued messages whilst also continuing to handle and print the new messages]

In which case, you'd need your standard A-E threads, in addition to another thread (which I'll call F) which prints the messages to screen for B - E. A would operate as normal, B - E would all add their messages for printing to a queue. Thread F would then read the queue, and print to screen when able. This means that you'd only needs thread A and F to synchronize with each other.

[Edited by - TheUnbeliever on April 19, 2007 1:42:07 PM]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!