Method or Extension Method to Handle InvokeRequired

心已入冬 提交于 2019-12-12 10:17:23

问题


I can't quite come up with the solution to creating a generic method to handle the InvokeRequired for void methods (I'll deal with return values later). I was thinking something like:

// 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()
  }
}

Then I could write something like:

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

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

This doesn't compile obviously, I just can't quite tie it together.


回答1:


Hans is correct, in that you probably don't want to wrap code like this up, especially since it can cause some debugging issues down the road in determining what thread actions are happening on. That said, this would be the signature you'd want:

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



回答2:


Loose Action parameters of "object,object" (as JerKimball suggests), name it SafeInvoke, and attach to event via anonymous delegate:

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


来源:https://stackoverflow.com/questions/14106357/method-or-extension-method-to-handle-invokerequired

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!