user4063382
user4063382

Reputation:

What is the purpose of backgroundworker in c#?

I am kind of new to c# and I am required to create a client server chat. Our professor gave us the following as a small hint to get us going. But I do not understand what the backgroundworker does.

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

Upvotes: 0

Views: 87

Answers (1)

Emile P.
Emile P.

Reputation: 3962

The BackgroundWorker class is designed to execute operations on a seperate thread, whilst reporting to the main thread through the ProgressChanged and RunWorkerCompleted events. The example your professor provided is far from a typical implementation of the class, and a backgroundworker should probably not be used for something like that.

Upvotes: 1

Related Questions