I have a thread that runs in the background during an asynchronous download. The purpose of the thread is to identify whether or not the download has stopped. My code basically says "if we haven't downloaded any more bytes in the last 10 seconds, assume the download has failed and do this".
When I tried to update a label on my WPF window saying the download had stopped, I was told I couldn't access it from a non-static reference. So I added MainWindow main = new MainWindow()
, and then added that to the variable to keep from needing the WPF element to be static. But I also needed to use a Dispatcher
because another thread already owned that object. So my code looked like this:
MainWindow main = new MainWindow();
main.Dispatcher.BeginInvoke(new Action(delegate() {
main.mainTitle.Content = "Unable to connect to the internet";
}));
That didn't change anything though, so I changed my approach. I changed the Dispatcher
to this:
MainWindow main = new MainWindow();
Application.Current.Dispatcher.BeginInvoke(new Action(delegate() {
main.mainTitle.Content = "Unable to connect to the internet";
}));
However, this appeared to do nothing because on the line that changes the content of the WPF item, I received the error 'The calling thread cannot access this object because a different thread owns it.'
How can I change this object's content from another thread, and why isn't the Dispatcher
working?