Search code examples
c#.netmultithreadingthread-safetythread-synchronization

Console.writeline() multithreading problems


I am trying to mock up of a chat client. First here's the code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace thread
{
    class Program
    {

    public static Thread t1;
    public static Thread t2;
    public static bool flag;
    public static Random rand = new Random();

    static void Main(string[] args)
    {
        t1 = new Thread(first);
        t2 = new Thread(second);
        t1.Start();
        t2.Start();

        Console.Read();
    }

    public static void first()
    {

        string[] phrase = { "Hello", "random", "blah,blah", "computer", "Welcome", "This is chat bot" };
        while (!flag)
        {
            Thread.Sleep(4000);
            Console.WriteLine("{0}", phrase[rand.Next(6)]);
        }
    }

    public static void second()
    {
        string input = "";
        while (input!="x")
        {

            input=Console.ReadLine();
            if (input=="x")
            {
                break;
            }

        }
        flag = true;
    }


   }
}

Ok so this program would automatically print some text on console, and i can write my message on the screen too. Now the problem is that whenever i am typing a long sentence, anything that takes more than 4 seconds to type. Then instead of the automated message being printed on the next line it just gets append to whatever i am typing. I am really new to multi threading so i am not exactly sure what's the problem. I think both the threads are using the same console class.

Help would be appreciated in this regard.


Solution

  • Implementing a Chat client in the Console is very difficult. It's possible, but it's not at all trivial.

    It is much easier to implement it in a GUI-based environment, such as winforms, where you can have two entirely separate text areas, one for input and one for output.

    In order to do this in a console you would need to, whenever you needed to display test, move the cursor up to a previous line, write out that text, and then move the cursor back to where the user had it for input. But doing that would over-write the previous line of text, so that previous line of text would need to be written on the line before that, and so on and so forth until you get to the top of the buffer, where the line can be removed entirely. On top of that, you can't read information from the console, so you'll need to keep track of everything in memory so you can do this whole write out.

    Doing everything in a winform is much, much easier. To write out information just add it to the text in the output textbox, and to read information, when the "send" button or enter is pressed, just clear the input textbox and process it's contents. You don't need to worry about the interaction between those two.