简体   繁体   English

填充数组时出现System.InvalidOperationException错误

[英]System.InvalidOperationException error when populating an array

So I have a program that works as the UI for a console app. 因此,我有一个可用作控制台应用程序UI的程序。 I tried to add a progress bar to it. 我试图添加一个进度条。 When the user clicks on the Start button, it does this: 当用户单击“ Start按钮时,它将执行以下操作:

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. 这是为了在GUI程序工作并提供控制台程序时更新进度条。 When the program starts populating the array called filemap like this: 当程序开始填充名为filemap的数组filemap如下所示:

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: 在您的CompilerReport方法中的某处,您需要这样的东西:

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. 您无法从后台线程访问ProjectLocation.Text You can only access members of a UI control on the thread on which it was originally created. 您只能在最初创建UI线程的线程上访问UI控件的成员。

So if you want the current text of ProjectLocation in your DoWork event handler, you should use the dispatcher: 因此,如果要在DoWork事件处理程序中使用ProjectLocation的当前文本,则应使用分派器:

string location = Dispatcher.Invoke(() => ProjectLocation.Text);
filemap = Directory.GetFiles(location + "\\www\\js\\", "*.js");

Or pass it as an argument to the RunWorkerAsync method. 或将其作为参数传递给RunWorkerAsync方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM