BackgroundWorker
has built in support for reporting the current progress of the work, which sounds like it's exactly what you're doing:
var worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += (s, args) =>
{
while (true)
{
Thread.Sleep(1000);//placehodler for real work
worker.ReportProgress(0, "Still working");
}
};
worker.ProgressChanged += (s, args) =>
{
textBox1.Text = args.UserState as string;
};
worker.RunWorkerAsync();
By leveraging the built in support you allow the background worker to handle marshaling to the UI thread. (It will ensure that all of the events besides DoWork
run in the UI thread.)
This also has the advantage of separating the UI logic from the business logic, rather than embedding code for manipulating the UI all throughout code doing business work.