gpt4 book ai didi

c# - 使用 BeginInvoke 动态添加 ListView 项时出现 "The calling thread must be STA, because many UI components require this."

转载 作者:行者123 更新时间:2023-11-30 17:42:06 28 4
gpt4 key购买 nike

我正在尝试从 BackgroundWorker 调用一个方法,将用户控件添加到 ListView:

private void AddItems(List<FileItem> fileItems) {
System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA);
Dispatcher.BeginInvoke(new Action(() => files.ItemsSource = fileItems));
}

用户控件 files 正在其构造函数中成功地从 fileItems 获取数据但是它抛出 调用线程必须是 STA,因为许多 UI 组件需要这个. 异常。我已经尝试将 [STAThread] 属性一一添加到所有父方法,但它仍然抛出异常。我应该在哪里添加这个属性?

更新

另请注意 Dispatcher.BeginInvoke(new Action(() => files.Items.Clear())); 正在正确执行。

最佳答案

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

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

另外an arbitrary object can be supplied in the ReportProgress方法;这允许将信息发送回 parent 。然后可以在事件处理程序中完成 UI 组件的处理,事件处理程序会自动在正确的 WPF/UI 线程上运行。 (同样适用于 'work complete' 处理。)

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

关于c# - 使用 BeginInvoke 动态添加 ListView 项时出现 "The calling thread must be STA, because many UI components require this.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32146994/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com