I was working one my recent WPF project today. I used multithreading in the project and recieved this error: The calling thread cannot access this object because a different thread owns it." This was happening because I was trying to change the properties of various UI elements from one of these threads I had created.
So, I researched the issue and read about the STAThread attribute and the consequences of derivation from DispatcherObject and how WPF application have two default threads; one dealing with UI elements and one with rendering. However, although it is apparently advisable to find other ways (other than multithreading) of implementing solutions in WPF, I wanted to find out how to work around this issue and avoid the above error.
I found a few things about delegates and using the Invoke() method and such, but nothing made any real sense. Therefore, I have made a basic mock up of the situation and I was hoping that someone could just outline,explain and help me to understand exactly how to eliminate the above error from the code, in addition to why the solution actually works. Here is the simple mock up:
Window1 Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
private Class1 c;
public Window1()
{
InitializeComponent();
c = new Class1(this);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
c.func1();
}
}
}
Class in which new thread is created
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace WpfApplication1
{
class Class1
{
private Window1 window;
private Thread thread;
public Class1(Window1 window)
{
this.window = window;
}
public void func1()
{
try
{
thread = new Thread(new ThreadStart(func2));
thread.Start(); //I obviously get the error here as I start the func2 method in the new thread and try to change the button content from the new thread
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.Message);
}
}
public void func2()
{
window.button1.Content = "Hello"; //this is a button on the Window WPF Application
}
}
}
Any help and guidance with this issue would be greatly appreciated.
Thanks you very much for you time.

New Topic/Question
Reply
MultiQuote








|