为文本框事件运行线程 [英] Running a thread for Text box event
问题描述
我有一个文本框,通过文本框我正在聊天,这个文本框不断被使用,因此它阻止了我的程序UI其他控件。所以我想为我的文本框事件制作一个帖子。所以我不会阻止我的程序UI。考虑下面作为我想要创建线程的文本框事件。
private void textBox1_KeyDown(object sender,KeyEventArgs e)
{
}
那怎么可能???我想在C#.Net中做这件事.....谢谢......
你不应该这样做。您应该为聊天通信创建一个工作线程,并将数据从文本框传递给这样的工作线程(参见如何:对Windows窗体控件进行线程安全调用 [ ^ ])。
我建议使用线程池,排队将数据发送到服务器的逻辑。
ThreadPool.QueueUserWorkItem(SendData, data);
然后,您可以使用逻辑定义SendData函数在KeyDown处理程序中写道。
public void SendData( object inputParam)
{
try
{
string input = inputParam as string ;
writer.Write(Form1.GetSysName()+ : + input); // 发送至服务器
...
}
< span class =code-keyword> catch (SocketException se)
{
output_text.Text + = \ n错误等待对象;
}
}但是,如果您希望以同步的方式发送消息,那么线程池将不是一个好选择,你可能只是产生一个线程。
线程th = 新线程(SendData );
th.Start();但是,您可能还需要定义一种机制来排队请求。
I have a textbox , through textbox i am doing chat and this textbox is continuously being used hence it has blocked my program UI other controls . So i want to make a thread for my textbox event . So that i would not block my program UI . Consider below as a textbox event for which i want to make a thread.
private void textBox1_KeyDown(object sender,KeyEventArgs e)
{
}
So how its Possible ??? I want to do it in C# .Net ..... Thanks ...
You shouldn't do that. You should instead create a worker thread for the chat communication and pass data to such worker thread from your text box (see "How to: Make Thread-Safe Calls to Windows Forms Controls"[^]).
I would recommend to use a thread pool, to queue your logic of sending data to server.
ThreadPool.QueueUserWorkItem(SendData, "data");then, you may define the SendData function with the logic you wrote in the KeyDown handler.
public void SendData(object inputParam) { try { string input = inputParam as string; writer.Write(Form1.GetSysName() + " : " + input); // Send to Sever ... } catch (SocketException se) { output_text.Text += "\n Error waiting Object"; } }However, if you want your messages to be sent in synchronized way then, threadpool will not be a good choice, there you may just spawn a thread.
Thread th = new Thread(SendData); th.Start();
But, you may also need to define a mechanism to keep queuing your requests.
这篇关于为文本框事件运行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!