我正在尝试模拟一个聊天客户端。首先,下面是代码
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;
}
}
}好的,所以这个程序会自动在控制台上打印一些文本,我也可以在屏幕上写下我的消息。现在的问题是,每当我输入一个长句子时,任何超过4秒的内容都会被输入。然后,自动消息不会打印到下一行,而只是附加到我键入的内容之后。我对多线程还是个新手,所以我不太确定问题出在哪里。我认为这两个线程都使用相同的控制台类。
在这方面,我们将不胜感激。
发布于 2012-10-31 04:06:21
在控制台中实现聊天客户端是非常困难的。这是可能的,但这并不是微不足道的。
在基于GUI的环境中实现它要容易得多,比如winforms,在这种环境中可以有两个完全独立的文本区域,一个用于输入,一个用于输出。
为了在控制台中执行此操作,无论何时需要显示测试,都需要将光标向上移动到前一行,写出该文本,然后将光标移回用户输入的位置。但这样做将覆盖前一行文本,因此前一行文本将需要写入之前的行,依此类推,直到您到达缓冲区的顶部,在那里可以完全删除该行。最重要的是,您不能从控制台读取信息,因此您需要跟踪内存中的所有内容,以便可以执行整个写出操作。
在winform中做任何事情都要容易得多。要写出信息,只需将其添加到输出文本框中的文本,而要读取信息,当按下“发送”按钮或回车时,只需清除输入文本框并处理其内容。您不需要担心这两者之间的交互。
发布于 2012-10-31 04:02:20
使用Console描述类似聊天的应用程序是不切实际的。
显然,这是一种方法,但在Console中实现它真的很困难。
发布于 2016-01-14 17:03:16
Lol 2ez
public static void WriteLineMultithread(string strt) {
int lastx=Console.CursorLeft,lasty=Console.CursorTop;
Console.MoveBufferArea(0,lasty,lastx,1,0,lasty+1,' ',Console.ForegroundColor,Console.BackgroundColor);
Console.SetCursorPosition(0,lasty);
Console.WriteLine(strt);
Console.SetCursorPosition(lastx,lasty+1);
}此方法允许您在用户正在另一个线程上使用"Console.ReadLine()“时编写消息。我假设聊天消息的接收是异步的,或者发生在另一个线程上。
您可以添加一些lock(){},这将是完美的。
https://stackoverflow.com/questions/13146551
复制相似问题