Robert Harvey
Robert Harvey

Reputation: 180777

Making a Controls.Add method call thread-safe

Let's say I have the following code:

public void Inject(Form subform)
{
    this.tabControl1.TabPages[1].Controls.Add(subform);
    this.Refresh();
}

How can I convert the Controls.Add() call to a thread-safe call, using Control.Invoke?

Upvotes: 1

Views: 826

Answers (1)

JaredPar
JaredPar

Reputation: 754585

The only way to make Control.Add thread safe is to make sure it's called from the UI thread. This also implies that the Control being added is usable from the UI thread.

Here is a function though which produces a delegate which can add to a Control from any thread (presuming the added Control is OK on the UI thread).

public Action<Control> GetAddControl(this Control c) 
{
  var context = SynchronizationContext.Current;
  return (control) =>
  {
     context.Send(_ => c.Controls.Add(control), null);
  };
}

Then for a given Control you can pass the resulting delegate to any thread.

// From UI thread
Action<Control> addControl = c.GetAddControl();

// From background thread 
addControl(subForm);

Upvotes: 3

Related Questions