处理InvokeRequired的方法或扩展方法

时间:2012-12-31 21:59:04

标签: c# winforms events delegates extension-methods

我无法提出创建泛型方法来处理void方法的InvokeRequired的解决方案(稍后我会处理返回值)。我想的是:

// Probably not the best name, any ideas? :)
public static void CheckInvoke(this Control instance,
                               ,Action<object, object> action)
{
  if (instance.InvokeRequired)
  {
    instance.Invoke(new MethodInvoker(() => action));
  }
  else
  {
    action()
  }
}

然后我可以这样写:

public partial class MyForm : Form
{
  private ThreadedClass c = new ThreadedClass();

  public MyForm()
  {
    c.ThreadedEvent += this.CheckInvoke(this
                                        ,this.MethodRequiresInvoke
                                        ,sender
                                        ,e);
  }
}

这显然不能编译,我只是不能把它绑在一起。

2 个答案:

答案 0 :(得分:2)

汉斯是正确的,因为你可能不希望包装这样的代码,特别是因为它可能导致一些调试问题,以确定正在发生的线程动作。也就是说,这将是你想要的签名:

public static class FormsExt
{
    public static void UnwiseInvoke(this Control instance, Action toDo)
    {
        if(instance.InvokeRequired)
        {
            instance.Invoke(toDo);
        }
        else
        {
            toDo();
        }
    }
}

答案 1 :(得分:1)

“对象,对象”的松散动作参数(如JerKimball建议的那样),将其命名为SafeInvoke,并通过匿名委托附加到事件:

 c.ThreadedEvent += delegate
                        {
                           c.SafeInvoke(this.MethodRequiresInvoke);
                        };