[英]What is the purpose of backgroundworker in c#?
我是C#的新手,并且需要创建客户端服务器聊天室。 我们的教授给了我们以下内容,作为使我们前进的一个小提示。 但是我不知道背景工作者会做什么。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) // Receive data
{
while (client.Connected)
{
try
{
receive = streamreader.ReadLine();
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("You : " + receive + "\n"); }));
receive = "";
}
catch (Exception x)
{
MessageBox.Show(x.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) // Send data
{
if (client.Connected)
{
streamwriter.WriteLine(text_to_send);
this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Me : " + text_to_send + "\n"); }));
}
else
{
MessageBox.Show("Send failed!");
}
backgroundWorker2.CancelAsync();
}
BackgroundWorker类旨在在单独的线程上执行操作,同时通过ProgressChanged和RunWorkerCompleted事件向主线程报告。 您的教授提供的示例与该类的典型实现方式相去甚远,并且可能不应将背景工作人员用于此类工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.