So I have a program that works as the UI for a console app. I tried to add a progress bar to it. When the user clicks on the Start
button, it does this:
MainProgress.Value = 0;
MainProgress.Maximum = PackageNwCheckbox.IsChecked == true ? 4 : 3;
BackgroundWorker compilerWorker = new BackgroundWorker();
compilerWorker.WorkerReportsProgress = true;
compilerWorker.DoWork += StartCompiler;
compilerWorker.ProgressChanged += CompilerReport;
compilerWorker.RunWorkerAsync();
This is in order to update the progress bar when the GUI program works and feeds the console program. When the program starts populating the array called filemap
like this:
filemap = Directory.GetFiles(ProjectLocation.Text + "\\www\\js\\", "*.js");
//The variable is an array of strings.
The app crashes and the error says
The call thread couldn't access the item because another thread has it.
In desktop applications with background threads, if you're attempting to update a view. You will need to invoke that update with the dispatcher. Somewhere in your CompilerReport
method you want something like this:
MainProgress.Dispatcher.Invoke(() =>
{
// Do update here
});
With more code, I could probably detail a better answer
You can't access ProjectLocation.Text
from a background thread. You can only access members of a UI control on the thread on which it was originally created.
So if you want the current text of ProjectLocation
in your DoWork
event handler, you should use the dispatcher:
string location = Dispatcher.Invoke(() => ProjectLocation.Text);
filemap = Directory.GetFiles(location + "\\www\\js\\", "*.js");
Or pass it as an argument to the RunWorkerAsync
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.