Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF progress bar update with dispatcher

I am trying to update a progressbar using the dispatcher but somehow cannot think where to place the dispatcher.Invoke and what to pass inside it.

Im trying to import files and needs to show the user how many files are imported using the progress bar.

so I have a delegate:

public delegate void DelegateA(ProgressClass progressClass);

im calling the delegate and passing the function to call.

DelegateA(FunctionA);

so while importing each file it calls the FunctionA.

private void FunctionA(ProgressClass progressClass)
{
    **//Put dispatcher.invoke here?**
    progressbar.updateprogress(progressclass);
    progressbar.show();
}

The progressclass has two properties which sets the progressbar's value(how many have been processed) and total items to process.

I can't understand what delegate method to pass in InvokeMethod(THreadPriority, delegate method)?

Sorry, if something is not clear.

like image 751
alice7 Avatar asked May 17 '11 19:05

alice7


2 Answers

If you are trying to update the UI from some non-UI thread you can do something like this..

//here progress bar is a UIElement
progressBar.Dispatcher.BeginInvoke(
           System.Windows.Threading.DispatcherPriority.Normal
           , new DispatcherOperationCallback(delegate
                   {
                       progressBar1.Value = progressBar1.Value + 1;
                       //do what you need to do on UI Thread
                       return null;
                   }), null);

This code is taken from a good post about updating UI from background thread

like image 50
Haris Hasan Avatar answered Nov 08 '22 08:11

Haris Hasan


I am assuming that you've started a background thread to import the files. You should consider using BackgroundWorker for this, which is lightweight and has a mechanism built in to report progress (e.g., a ProgressBar) using an event.

If you want to use a new thread, anywhere within the processing that you are doing, just declare a delegate, add a function to target, and call Dispatcher.BeginInvoke:

Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateProgressDelegate(UpdateProgress), myProgressData);

//...

private delegate void UpdateProgressDelegate(ProgressClass progressClass);

void UpdateProgress(ProgressClass progressClass)
{
    progressbar.updateprogress(progressclass);
    progressbar.show(); 
}
like image 37
Ed Bayiates Avatar answered Nov 08 '22 06:11

Ed Bayiates