WPF in WinForms (Elementhost) Error on base.Dispose(disposing)

Hi All,

I am working with C# and I have a user control in WPF, my problem is that when I close the form where my usercontrol is instantiated I get the following error in the base.Dispose(disposing) line of the .Designer.cs file of the form.

See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.InvalidOperationException: The calling thread cannot access this object because a different thread owns it.
   at System.Windows.Threading.Dispatcher.VerifyAccess()
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Input.FocusManager.SetFocusedElement(DependencyObject element, IInputElement value)
   at System.Windows.Forms.Integration.ElementHost.OnLeave(EventArgs e)
   at System.Windows.Forms.Control.NotifyLeave()
   at System.Windows.Forms.ContainerControl.UpdateFocusedControl()

This does not occur when I don't instantiate the WPF control. To instantiate the usercontrol I use the ElementHost class to integrate the WPF control in my WindowsForm application.

I don't know if anyone has an advice to resolve this problem?

Thanks in advance.
Javier MendezAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
This error is, most likely, occurring because you are calling dispose from your main thread and the WPF instance has a control within it that is being accessed from a different thread.  What you need to do is implement an Invoke If Required pattern; e.g. -
static class Extensions
{
	public static void HandleInvokeRequired<T>(this T Control, Action<T> Action) where T : Control, ISynchronizeInvoke
	{
		//Check to see is the control is not null
		if (Control == null)
			throw new ArgumentNullException(string.Format("Cannot execute {0} on {1}.  {1} is null.", Action, Control));

		//Check to see if the control is disposed.
		if (Control is Control && (Control as Control).IsDisposed)
			throw new ObjectDisposedException(string.Format("Cannot execute {0} on {1}.  {1} is disposed.", Action, Control));

		//Check to see if the handle is created for the control.
		if (Control is Control && !(Control as Control).IsHandleCreated)
			throw new InvalidOperationException(string.Format("Cannot execute {0} on {1}.  Handle is not created for {1}.", Action, Control));

		//Check to see if the control's InvokeRequired property is true
		if (Control.InvokeRequired)
		{
			try
			{
				//Use Invoke() to invoke your action
				Control.Invoke(Action, new object[] { Control });
			}
			catch (Exception ex)
			{
				throw new Exception(string.Format("Cannot execute {0} on {1}.  {2}.", Action, Control, ex.Message));
			}
		}
		else
		{
			try
			{
				//Perform the action
				Action(Control);
			}
			catch (Exception ex)
			{
				throw new Exception(string.Format("Cannot execute {0} on {1}.  {2}.", Action, Control, ex.Message));
			}
		}
	}
}

Open in new window

Usage:
TextBox tb = new TextBox();
tb.HandleInvokeRequired(c => c.Text = "Text Here");

Open in new window

-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.