i just have a strange problem and i didn't get why it happens. Could you please help me to find out why it happens and how i can fix it?
My error is: "The Calling Thread Cannot Access This Object Because A Different Thread Owns It".
My point is that getting some values from databese (it takes a long time therefore i use Task.Run()) and creating custom UI Component with the values and add into a wrap panel.
Firstly, i have an event which is window loaded:
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
await this.ShowAllMatchesAsync(); // This code workfully works
} // But after right here, it reports an error and doesn't show any code because it is in interrupt mode :(
I have a list which gets value by using async process:
private async Task ShowAllMatchesAsync()
{
List<Match> allMatches = await new GetValues().GetAllMatchValuesAsync(0); // This workfully works. So, allMatches value has some values which i need it to create UI Using Control:
// UI_MatchCard is a User Control which i have created
// This class needs a Match parameter, in this way it automatically creates MatchCard according to match value which i defined as parameter.
UI_MatchCard matchCard = new UI_MatchCard(allMatches[0]); // I just want to show first match of allMatches for this case.
// WP_Matches is a Wrap panel. I use it to add UI_MatchCard
this.WP_Matches.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });
// It workfully works here. I mean, it adds an UI_Matcherd to WP_Matches (this wrap panel) and count of Wp_Matches equals to 1 after adding it :)
}
When all process is done, it reports an error after processing where i told you (The last line of Windows_Loaded event).
The strange thing is that if I don't add an UI_MatchCard:
this.WP_Matches.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });
And if I add another UI component (like textblock)
this.WP_Matches.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(new TextBlock()); });
It doesn't report anything and workfully works. Also, if i add my UI_MatchCard without any parameter:
UI_MatchCard matchCard = new UI_MatchCard(); // Without any parameter
this.WP_Matches.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });
It workfully works again. But as you guess it doesn't show my match values. It just show blank match because i didn't enter the parameter.
Also these are what i have tried: Changing Invoke methodes:
this.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });
Application.Current.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });
And Task.ContinueWith() method.
How can i find out why it happens? Could you please help me?