Threadsafe manipulation of m:ui Control

Jan 25, 2014 at 8:36 AM
Hey guys,

I currently working on a simple crypto-chat application and came across a problem that's driving me nuts.

I've got 2 threads: At first the main application thread with window handles, and at second a thread for receiving incoming text messages. The second thread calls a callback to the Home.xaml.cs-Page in order to update a RichTextBox. This Callback crashes when accessing the RichtTextBox and says something like "This thread cannot access this object cause it's owned by another thread".
After some research I found some information about resolving this problem by using Invoke.
public MainWindow()
        {
            this.InitializeComponent();
            Thread t = new Thread(new ThreadStart(update));
            t.Start();
        }
        private void update()
        {
            //threadsafe call of "Application.Current.Shutdown"
            this.BeginInvoke(new Action(Application.Current.Shutdown));
        }
Unfortunately I cannot find a method "Invoke", "BeginInvoke" or any similar for the m:ui control objects.
So can anyone tell me how to update the RichTextBox or any other value of the control objects in a threadsafe way?

If you think I missed any important information, just ask for it. Hope you can help me with this problem.

Thx in advance, ep1stle
Jan 25, 2014 at 8:56 AM
Hi,

Invoke is what you should call, when you are using Windows Forms. Since you are using WPF, the Dispatcher is what you should use.
I don't know your application design, but you should also consider using async/await (if you are implementing .NET 4.5 or greater).

Hope this helps.
Marked as answer by ep1stle on 1/25/2014 at 2:48 AM
Jan 25, 2014 at 9:47 AM
Hey codedevote,

thx for your reply....now everthing is working!


For all the people who might have the same problem, here is how I use the dispatcher right now.
delegate void AddTextToChatBox(String text);

public void addMessageToChatBox(String text)
{
   //adding text to chatbox
   ChatBox.Documents.Add(...);
}
public void MessageReceivedCallback(Object sender, MessageReceivedEventArgs e)
{
   //Thread-unsafe call
   addMessageToChatBox(e.Message);

   //Thread-safe call using Dispatcher
   AddMessageCallback d = new AddMessageCallback(addMessageToChatBox);
   Dispatcher.BeginInvoke(d,new object[]{e.Text});
}