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()
ca开发者_JAVA百科ll to a thread-safe call, using Control.Invoke
?
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);
精彩评论