开发者

Making a Controls.Add method call thread-safe

开发者 https://www.devze.com 2023-04-01 07:06 出处:网络
Let\'s say I have the following code: public void Inject(Form subform) { this.tabControl1.TabPages[1].Controls.Add(subform);

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号