I have got a StartCommand Class:
public class StartCommand : ICommand
{
public void Execute(object parameter)
{
//Fill Listview1
...
//Here I want to increase the Progressbarvalue
//Fill Listview2
...
//Here again and so far..
}
}
Execute Command will be executed, when clicking the Startbutton on my MainWindow.xaml (where’s also the progressBar).
What I want now, is updating the Progressbar on these places (look at Code), while the ListViews are loading. How do I set up the Backgroundworker?
I tried something like that:
public class StartCommand : ICommand
{
MainWindow mainWindow;
public StartCommand(MainWindow mainWindow)
{
this.mainWindow = mainWindow
}
public void Execute(object parameter)
{
//Fill Listview1
...
mainWindow.backgroundWorker1.RunWorkerAsync(10);
//Fill Listview2
...
mainWindow.backgroundWorker1.RunWorkerAsync(20);
}
}
MainWindow:
public partial class MainWindow : Window
{
BackgroundWorker backgroundWorker1;
public MainWindow()
{
InitializeComponent();
InitializeBackgroundWorker();
}
private void InitializeBackgroundWorker()
{
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(
backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged +=
new ProgressChangedEventHandler(
backgroundWorker1_ProgressChanged);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = UpdateProgressBar((int)e.Argument, worker);
}
private int UpdateProgressBar(int value, BackgroundWorker worker)
{
worker.ReportProgress(value);
return Convert.ToInt32(progressBar.Value);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
}
}
Thats not working (This is only some Copy/Paste arrangement, cause I have no idea on how to accomplish that, working first time with Threads in WPF). But maybe u got now a better sight, of what I’m looking for..
You have to choose: use one background worker to load all the listviews or use multiple background workers, each filling a listview.
Currently you are trying to force the backgroundworker to start working on another job before the previous job has finished.
To fix this quickly: put all the code to load the listviews in the DoWork handler.
To use multiple Backgroundworkers create multiple Backgroundworkers: