C# 中后台工作者的目的是什么?

本文关键字:是什么 工作者 后台 | 更新日期: 2023-09-27 18:37:11

我是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();
}

C# 中后台工作者的目的是什么?

BackgroundWorker 类旨在在单独的线程上执行操作,同时通过 ProgressChanged 和 RunWorkerCompleted 事件向主线程报告。您的教授提供的示例远非该类的典型实现,并且可能不应该将后台工作者用于类似的事情。