I'm implementing a UI which contains a list I use the framework MVVMCross. To fill the list I iterate through several directorys to gather specific XML documents. Now I want to outsource this iterating process in a different thread do prevent the MainWindow from freezing and show a loading wheel or progress bar. If I start this function I get the Exception that i have to start the thread from a dispatcher thread, but I'am starting it already from a dispatcher thread, on my point of view. What I'am doing wrong ?
readonly Dispatcher _dispatcher;
public HomeViewModel(IMvxNavigationService navigationService)
{
NavigationService = navigationService;
_dispatcher = Dispatcher.CurrentDispatcher;
}
private async void StartDispatcher()
{
BackgroundWorker _backgroundWorker = new BackgroundWorker();
_backgroundWorker.DoWork += _backgroundWorker_DoWork;
Delegate action = new Action(_backgroundWorker.RunWorkerAsync);
await _dispatcher.BeginInvoke(action, DispatcherPriority.Normal);
}
private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
LoadingProcess();
}
Tried several approaches to start the thread with the dispatcher, but nothing work.
The typical way to do work in the background is:
Everything with Cancellation & Progress is optional, and require you to have some control that report progress and do cancellation.
What you are trying to do makes little sense. If you ask the dispatcher to run something it will run it on the UI thread, so it will still block the UI. The main intent of the dispatcher is when you are running things on a background thread, and need to run something on the UI thread. However, I would recommend the async/await pattern, since that tend to make the code easier to read and understand.
You will need to ensure that
DoWorkInBackgroundis thread safe, and do not use any shared, mutable, data structures without proper synchronization. Try to keep the method "Pure" if possible.