2

I have written a simple Chat Application in console c# that is multi-threaded and allows for input and output to work at the same time. However, my console input often becomes mixed with console output because of it being multi-threaded.

For Example:

enter image description here

Is there any way to solve this so that my console output can still be written and not interfere with my input? I would like to keep it in the console but I may move to a more graphical interface if needed.

Micho
  • 3,929
  • 13
  • 37
  • 40

2 Answers2

1

Save what is typed by the user and when a message comes, clear input with writing \b chars (backspace), then print the incoming message and then restore the user's input so it could continue to type.

Here's some basic code to illustrate the idea:

class Program
{
    static object locker = new object();
    static List<char> buffer = new List<char>();
    static void Main(string[] args)
    {
        new Thread(Chat).Start("John");
        string ourName = "Mike";
        buffer.AddRange(ourName + ": ");
        Console.Write(new string(buffer.ToArray()));
        while (true)
        {
            var k = Console.ReadKey();
            if (k.Key == ConsoleKey.Enter && buffer.Count > 0)
            {
                lock (locker)
                {
                    Console.WriteLine();
                    buffer.Clear();
                    buffer.AddRange(ourName + ": ");
                    Console.Write(buffer.ToArray());
                }
            }
            else
            {
                buffer.Add(k.KeyChar);
            }
        }
    }

    static Random rnd = new Random();
    static void Chat(object name)
    {
        var dlg = new[] { "Hello", "How are you", "I'm all right", "What a nice day" };
        while (true)
        {
            Thread.Sleep(3000 + rnd.Next(5000));
            lock (locker)
            {
                Console.Write(new string('\b', buffer.Count));
                var msg = name + ": " + dlg[rnd.Next(dlg.Length)];
                var excess = buffer.Count - msg.Length;
                if (excess > 0) msg += new string(' ', excess);
                Console.WriteLine(msg);
                Console.Write(new string(buffer.ToArray()));
            }
        }
    }
}
Mike Tsayper
  • 1,686
  • 1
  • 17
  • 25
-1

This is not a multithreading problem, this is a problem of how the command prompt on windows works. If your on windows 10 I would suggest switching to canocal bash and your problem will go away. If below windows 10 downloading a normal terminal through Git or cygwin.

Related questions with no answers.
how to handle different input/output in one console?
Prevent mixing of console output and written text

Community
  • 1
  • 1
Vans S
  • 1,743
  • 3
  • 21
  • 36