本文介绍了处理调用要求的方法或扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太想办法创建用于处理void方法的 InvokeRequired 的通用方法的方法(我将在后面处理返回值)。我在想类似的东西:

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.

推荐答案

汉斯(Hans)是正确的,因为您可能像这样包装代码,特别是因为在确定正在执行哪些线程操作时,它可能会导致一些调试问题。也就是说,这就是您想要的签名:

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

这篇关于处理调用要求的方法或扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:51