gpt4 book ai didi

c# - 在不访问 UI 线程的情况下在 BackgroundWorker 中获取 "UnauthorizedAccessException"

转载 作者:太空狗 更新时间:2023-10-29 23:25:27 27 4
gpt4 key购买 nike

我正在后台工作程序上做一些繁重的工作,因此它不会影响我的 Silverlight UI 线程。但是,在 DoWork 函数中我遇到了这个异常:

UnauthorizedAccessException“无效的跨线程访问”。

我知道我无法从 BackgroundWorker 访问 UI 线程,但是,此异常发生在这一行:

  ListBoxItem insert = new ListBoxItem();

如何访问我的 ui 线程?

这是我缩小范围后的实际代码片段。我基本上是在创建我想插入到 sourceList 列表框的列表框项目:

void FillSourceList()
{
busyIndicator.IsBusy = true;
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (sender, args) =>
{
List<ListBoxItem> x = new List<ListBoxItem>();
for (int i = 0; i < 25; i++ )
{
ListBoxItem insert = new ListBoxItem(); //<---Getting exception here
insert.Content = "whatever";
x.Add(insert);
}
args.Result = x;
};
bw.RunWorkerCompleted += (sender, args) =>
{
foreach (ListBoxItem insert in (List<ListBoxItem>)(args.Result))
sourceList.Items.Add(insert);
busyIndicator.IsBusy = false;
};

bw.RunWorkerAsync();
}

最佳答案

ListBoxitem 派生自 Control,因此它被视为 GUI 的一部分。我原以为“分离”的项目在线程中也可以,但显然不是。

显而易见的解决方案:构建一个包含内容(字符串)的列表 x 并将 Items 的创建延迟到 Completed 事件。

关于c# - 在不访问 UI 线程的情况下在 BackgroundWorker 中获取 "UnauthorizedAccessException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9517757/

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