WPF Controls has no ‘InvokeRequired’/’Invoke’ like WinForms, so making accessing a WPF Window/Control threadsafe can be accomplished by using the System.Windows.Threading.Dispatcher. Here are some examples. First a property: 

 

public int Progress
{
	get
	{
		if (!Dispatcher.CheckAccess())
		{
			Func<int> f = delegate () { return Progress; };
			return Dispatcher.Invoke(f);
		}

		...
	}
	set
	{
		if (!Dispatcher.CheckAccess())
		{
			Action<int> a = delegate (int progress) { Progress = progress; };
			Dispatcher.Invoke(a);
			return;
		}

		...
	}
}

 

  A void method

 

 

public void SetProgress(object obj, int progress)
{
	if (!Dispatcher.CheckAccess())
	{
		Action<object, int> a = new Action<object, int>(SetProgress);
		Dispatcher.Invoke(a, DispatcherPriority.Normal, obj, progress);
		return;
	}

	...
}

 

And lastly a method with a return value

 

 

public bool AllProcessesDone()
{
	if (!Dispatcher.CheckAccess())
	{
		Func<bool> f = new Func<bool>(AllProcessesDone);
		return Dispatcher.Invoke(f, DispatcherPriority.Normal);
	}

	...
}

 

As always, feel free to comment, or ask.

 


InvalidOperationException: "Cross-thread operation not valid: Control '<name>' accessed from a thread other than the thread it was created on."

If you are getting this exception it means that your are trying to access a Control - running on the main thread of your application, say ThreadA - from another thread, ThreadB.

This other ThreadB could of-course be either a

System.Threading.Thread

 or a

System.ComponentModel.BackgroundWorker

or whatever.


The way to get around this, is by using invocation in the Control.


Here is a example if you don’t need a return value:

public void AddMessage(MessageType type, Message message)
{
    internalAddMessage(type, message);
}

private void internalAddMessage(MessageType type, Message message)
{
    if (this.InvokeRequired)
    {
        this.Invoke((MethodInvoker)delegate { internalAddMessage(type, message); });
        return;
    }
    //Do the 'Add Message' stuff you want to do
}

or if you need a return value from the Invoked method:

 

private DialogResult internalShowDialog()
{
    if (this.InvokeRequired)
    {
        Func<DialogResult> func = new Func<DialogResult>(internalShowDialog);
        return (DialogResult)this.Invoke(func);
    }
    else
    {
        return this.ShowDialog();
    }
}