can some one explain why I face problem with backgroundworker
backgroundWorker1_RunWorkerCompleted works just fine and sends the text to the textbox1
but
backgroundWorker1_DoWork does not work!
it should to send the text “Working…” to the textbox1, but I get error with
textBox1.Text = textBox1.Text + Environment.NewLine + DateTime.Now +@” >> ” +str;
the error I get is related to Cross-Thread
any one can help?
cheesr
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace FolderWatchingGUI01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void output(string str)
{
textBox1.Text = textBox1.Text + Environment.NewLine + DateTime.Now +@" >> " +str;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
output("Working ...");
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
output("Work Completed");
}
private void button1_Click(object sender, EventArgs e)
{
button2.Enabled = true;
button1.Enabled = false;
output("Starting Work");
backgroundWorker1.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
output("Work Canceld");
button2.Enabled = false;
button1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Edit
I seems able to solve the issue with:
is this solution a proper way? or it is a dirty workaround and I should not do it!?!
delegate void outputCallback(string text);
public void output(string str)
{
if (textBox1.InvokeRequired)
{
outputCallback d = output;
Invoke(d, new object[] { str });
}
else
{
textBox1.Text = textBox1.Text + Environment.NewLine + DateTime.Now +@" >> " +str;
}
}
This is by design. DoWork() runs on another Thread and should not use any GUI components. In Debug mode his is immediately spotted and trapped.
If you run this outside of the debugger it will (almost always) work. But very rarely things will go wrong, a hard to catch bug.
Basically, your output should look something like:
Also, you should check
e.Errorin the Completed eventhandler.