I\'m creating a backup utility in WPF and have a general question about threading:
In the method backgroundWorker.DoWork(), the sta
There's no way you can directly access the UI from another thread. The only solution is to raise an event in the thread and then catch it in the UI thread.
If you don't want to use a BackgroundWorker thread you'll need something like this to raise the event in the thread:
// Final update
if (Library_Finished != null)
{
Library_Finished(this, null);
}
which is declared like this:
public event EventHandler Library_Finished;
Then you'll need something like this in the UI thread to catch and process the event:
private void Library_Finished(object sender, EventArgs e)
{
Action action = () => FinalUpdate();
if (Thread.CurrentThread != Dispatcher.Thread)
{
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, action);
}
else
{
action();
}
}
But even if you use a BackgroundWorker you'll still need to implement the thread checking code before accessing the UI elements.
Your best option is to continue using .ReportProgress and .ProgressChanged. Is there a particular reason this isn't sufficient?
Have you looked at using Dispatcher.Invoke?
Dispatcher.Invoke(new Action(() => { Button_Start.Content = i.ToString(); }));
Or use BeginInvoke if you want something to happen asynchronously.