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

Dav*_* S. 5 c# asp.net silverlight

我在背景工作者身上做了一些繁重的工作,所以它不会影响我的Silverlight UI线程.但是,在DoWork函数中,我遇到了这个异常:

UnauthorizedAccessException "无效的跨线程访问".

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

  ListBoxItem insert = new ListBoxItem();
Run Code Online (Sandbox Code Playgroud)

怎么访问我的ui线程?

这是我将其缩小到的实际代码段.我基本上正在创建listboxitems,我想插入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();
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 4

AListBoxitem派生自 Control,因此它被视为 GUI 的一部分。我本以为“独立”项目在线程中也可以,但显然事实并非如此。

显而易见的解决方案:构建x内容列表(字符串)并将项目的创建延迟到完成事件。