Actually not, you need to report progress not from but to an (already existing) STA thread, in which the UI runs.
You can achieve this either through BackgroundWorker
functions (ReportProgress
is delivered on the thread which started the BackgroundWorker
-- this should be your UI thread), or using the UI thread's Dispatcher
(usually with Dispatcher.BeginInvoke
).
Edit:
For your case, the solution with BackgroundWorker
won't work, as its thread is not STA. So you need to work with just usual DispatcherlInvoke
:
// in UI thread:
Thread thread = new Thread(PrintMethod);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
void PrintMethod() // runs in print thread
{
// do something
ReportProgress(0.5);
// do something more
ReportProgress(1.0);
}
void ReportProgress(double p) // runs in print thread
{
var d = this.Dispatcher;
d.BeginInvoke((Action)(() =>
{
SetProgressValue(p);
}));
}
void SetProgressValue(double p) // runs in UI thread
{
label.Content = string.Format("{0}% ready", p * 100.0);
}
In case your current object does not have a Dispatcher
, you can take it from your UI objects or view model (if you use one).