0

I have created an async function that creates a list of inlines and the list is returned. I can use the the list when received, but can't use to update Textblock component with the list.

it says:

An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code The calling thread cannot access this object because a different thread owns it.

I tried updating the Textblock within Dispatcher as i've seen in other answers but the same error persists.

my Code for generating inlines List:

private async Task<List<Inline>> getDataGridContent()
        {
            List<Inline> Inlines = new List<Inline>();
            int counter = 0;
            await Task.Run(()=>
            {
                foreach (string pin in pins.pins)
                {
                    counter++;                   
                    Run wall_e = new Run(" ]");                
                    wall_e.Foreground = Brushes.Red;
                    Run pin_run = new Run();                 
                    pin_run.Text = pin;
                    Inlines.Add(pin_run);
                    Inlines.Add(wall_e);
                  
                }
            });                               
              return Inlines;          
        }

calling function :

  async void updateGrid()
            {
                datagird.Text = "";
                Cur_count.Content = pins.TOTAL;
                List<Inline> inlines =  await getDataGridContent();
                Debug.WriteLine(inlines.Count);    // this works and i can use the list here        
                datagird.Inlines.AddRange(inlines); 
               // this gives the error. this works if i create a list here itself 
               // and pass it. it does'nt work with the list returned by getDataGridContent();
            }
django
  • 41
  • 1
  • 5
  • Can you try to change the signature of your `updateGrid()` method from `async void` to `async Task` and check if you still encounter this issue? – Volodymyr Nov 07 '21 at 19:07
  • You can't create UI elements (DispatcherObject types) on a background thread and pass them to the UI thread except the object is a Freezable and frozen. UI elements must be created on the UI thread. – BionicCode Nov 07 '21 at 19:14
  • You should create data models and bind them to the view and use DataTemplates to define the UI. You should not generate UI elements manually. – BionicCode Nov 07 '21 at 19:18

0 Answers0