-1

I want to make a grid element in wpf programmatically with c# code and because it needs a huge processing i used a thread for it.now when i want to assign it the visual studio says :

"The calling thread cannot access this object because a different thread owns it."

my code is something like this :

PrepareGrid gridMaker = new PrepareGrid();
Thread fetchGrid = new Thread(() => {
    GridContainer.Dispacher.Invoke(() => GridContainer.Content = gridMaker.getGrid());
});
fetchGrid.SetApartmentState(ApartmentState.STA);
fetchGrid.Start();

PrepareGrid is a class that prepares the grid and its getGrid's method returns the result grid and GridContainer is a WPF Scroll Viewer

i used nested dispatchers but it doesn't work


Why i can't use Task for wpf elements? the process of making grid is so huge and Thread uses only one core of processor as i know

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Javad
  • 63
  • 1
  • 9
  • I'm curious: did you make _any_ effort at all to research this question on your own? Bottom line: WPF UI objects have to be created in the same thread where they will be used. But also bottom line: you should not be creating UI objects in code-behind anyway. WPF has a very useful and efficient data binding model, which you can use to your advantage by creating _data_ object in a background thread, and then updating the UI in the UI thread once you're done with that. In the event that update is still time-consuming, you can take steps to do it incrementally so the UI remains responsive. – Peter Duniho Apr 27 '17 at 18:07
  • @PeterDuniho yes i did a lot of researches but non of them was my actual answer,what are those binding models? – Javad Apr 27 '17 at 18:15
  • 1
    See "MVVM", for starters. – Peter Duniho Apr 27 '17 at 18:19

1 Answers1

1

In WPF, you can have multiple UI threads, but a UI element must be used on the thread where it's created. You're creating it in the other thread, right? So you can't use it in the default UI thread.

I suspect the "huge processing" is not from the mere creation of the actual UI object at all. Find out exactly what the "huge processing" consists of, and put that on another thread. Or have your other thread invoke into the main UI thread when it creates the actual control or controls.