When your program starts out, at some place where you are sure you are in the UI thread, you can save the value of
Dispatcher.CurrentDispatcher
in an easily accessible location, e.g. a member variable named
_dispatcher
.
_dispatcher = Dispatcher.CurrentDispatcher;
Next, change the block of code that you have identified as caused a problem to a method:
private void AddMessageToNewForm(string userReceiver, string message)
{
chatForm = new ChatForm(chatWindowDict);
chatWindowDict.Add(userReciever, chatForm);
chatForm.userReciever = userReciever;
chatForm.userName = this.userName;
chatForm.tcpServer = this.tcpServer;
chatForm.formSender = this;
this.Form_Changer(chatForm);
this.add_chat_text("\n" + userReciever + " Says: \n" + message);
}
and then in place of all that code, use Dispatcher.Invoke to force the code to be run in the UI thread.
if (!chatWindowDict.ContainsKey(userReciever))
{
_dispatcher.Invoke(DispatcherPriority.Normal,
new Action<string, string>(AddMessageToNewForm), userReceiver, message);
}
I agree with the previous responder that the use of Invoke inside Form_Changer is not the right way to proceed.