I'm doing some heavy work on a backgroundworker, so that it doesn't affect my Silverlight UI thread. However, in the DoWork function I'm getting this exception:
UnauthorizedAccessException
"Invalid cross-thread access".
I know I can't access the UI thread from the BackgroundWorker, However, this exception occurs on this line:
ListBoxItem insert = new ListBoxItem();
How is that accessing my ui thread??
Here's the actual piece of code I've narrowed it down to. I'm basically doing work creating listboxitems which i'd like to insert to the sourceList
listbox:
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();
}
A ListBoxitem
derives from Control so it is considered part of the GUI. I would have expected a 'detached' item to be OK in a thread too but apparently it isn't.
The obvious solution: build up a list x
of Content (strings) and delay the creation of the Items to the Completed event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With