Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "UnauthorizedAccessException" in a BackgroundWorker without accessing UI thread

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();
}
like image 620
David S. Avatar asked Oct 09 '22 12:10

David S.


1 Answers

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.

like image 112
Henk Holterman Avatar answered Oct 12 '22 19:10

Henk Holterman