Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# &引用;调用线程必须是STA,因为许多UI组件都需要它;使用BeginInvoke动态添加ListView项时_C#_.net_Wpf_Multithreading_Listview - Fatal编程技术网

C# &引用;调用线程必须是STA,因为许多UI组件都需要它;使用BeginInvoke动态添加ListView项时

C# &引用;调用线程必须是STA,因为许多UI组件都需要它;使用BeginInvoke动态添加ListView项时,c#,.net,wpf,multithreading,listview,C#,.net,Wpf,Multithreading,Listview,我试图从BackgroundWorker调用一个方法,该方法将用户控件添加到ListView: private void AddItems(List<FileItem> fileItems) { System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA); Dispatcher.BeginInvoke(new Action(() => f

我试图从
BackgroundWorker
调用一个方法,该方法将用户控件添加到
ListView

private void AddItems(List<FileItem> fileItems) {
    System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA);
    Dispatcher.BeginInvoke(new Action(() => files.ItemsSource = fileItems));
}
private void附加项(列出文件项){
System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA);
Dispatcher.BeginInvoke(新操作(()=>files.ItemsSource=fileItems));
}
用户控件
files
在其构造函数中成功地从
fileItems
获取数据,但它抛出
调用线程必须是STA,因为许多UI组件都需要它。
异常。我已经尝试将
[STAThread]
属性一个接一个地添加到所有父方法中,但它仍然抛出异常。我应该在哪里添加此属性

更新


还请注意
Dispatcher.BeginInvoke(新操作(()=>files.Items.Clear())正在正确执行。

调度程序
指的是与BGW线程关联的调度程序,而不是WPF/UI线程。默认情况下,如果没有与当前线程关联,将创建一个新的调度程序/上下文;在上下文中,这是完全无用的

如果从启动BGW的UI线程提供dispatcher实例(),那么它“应该可以工作”。同样,正如Hans指出的,正确的(WPF/UI)dispatcher对象应该可以通过访问

附加方法;这允许将信息发送回父级。然后可以在事件处理程序中完成UI组件的处理,该事件处理程序将自动在正确的WPF/UI线程上运行。(处理时也适用此方法。)


无需为标准WPF项目设置任何STA线程选项/属性。

直接在列表视图控件上调用BiginInvoke,如下所示:

files.BeginInvoke(new Action(() => files.ItemsSource = fileItems));

线程已启动时,不能调用SetApartmentState()。不能任意应用[StatThread],它只在Main()入口点上工作。使用适当的调度程序Application.Current.dispatcher。您应该改用BackgroundWorker.ReportProgress或RunWorkerCompleted。@HansPassant请查看我的更新。正如我在用户2864740回复的评论中提到的那样,我尝试了你的方式。但是它又抛出了同样的异常并已启用
WorkerReportsProgress=true
。另外,在
ProgressChanged
事件中调用
files.ItemsSource=fileItems
。但它仍然不起作用。我做得对吗?“不工作”=?(在任何情况下,如果设置了所有项目,则可能应该在worker complete完成,而不是进行代表“进度”的增量更改。)为没有具体说明而道歉。但我的意思是,它仍然显示出同样的例外,那就是。。古怪的那就不知道了。如果源代码是可枚举的,那么可以尝试强制具体化源代码,例如,
worker.ReportProgress(90,fileItems.ToList())
(尽管由于它不是真正的“progress”,所以最好作为BGW的结果返回,并在工作完成处理程序中处理。)