【问题标题】:Creating a MethodInvoker function创建 MethodInvoker 函数
【发布时间】:2013-04-05 15:03:25
【问题描述】:

所以我有多线程我的应用程序。我遇到了这个错误“跨线程操作无效:控件从创建它的线程以外的线程访问。”

我的线程正在调用 Windows 窗体控件。所以为了解决这个问题,我使用了

Control.Invoke(new MethodInvoker(delegate { ControlsAction; }));

我正在尝试找出一种方法来制作这种通用方法,以便我可以重用代码并使应用程序更清洁。

例如,在我的调用中,我使用富文本框执行以下操作。

rtbOutput.Invoke(new MethodInvoker(delegate {    
rtbOutput.AppendText(fields[0].TrimStart().TrimEnd().ToString() + " Profile not   
removed.  Check Logs.\n"); }));

另一个是组合框,我只是在其中设置文本。

cmbEmailProfile.Invoke(new MethodInvoker(delegate { EmailProfileNameToSetForUsers = 
cmbEmailProfile.Text; }));

另一个例子是富文本框,我只是简单地清除它。

 rtbOutput.Invoke(new MethodInvoker(delegate { rtbOutput.Clear(); }));

我将如何创建一个可以为我执行此操作的通用函数,我只需要通过我希望它执行的操作传入控件?

这是我们迄今为止提出的。

private void methodInvoker(Control sender, Action act)
    {
        sender.Invoke(new MethodInvoker(act));
    }

所以问题类似于 appendtext,它似乎不喜欢。

【问题讨论】:

  • 对委托使用 Action 而不是 /。

标签: c# methods delegates


【解决方案1】:

这样的事情应该可以解决问题:

public static class FormsExt
{
    public static void InvokeOnMainThread(this System.Windows.Forms.Control control, Action act)
    {
        control.Invoke(new MethodInvoker(act), null);
    }
}

然后使用它就这么简单:

        var lbl = new System.Windows.Forms.Label();
        lbl.InvokeOnMainThread(() =>
            {
               // Code to run on main thread here
            });

使用您的原始标签:

        rtbOutput.InvokeOnMainThread(() =>
            {
               // Code to run on main thread here
               rtbOutput.AppendText(fields[0].TrimStart().TrimEnd().ToString() + " Profile not removed.  Check Logs.\n"); }));
            });

【讨论】:

  • 好吧,行动行动。如果它包含文本或类似内容怎么办。如果我将它传递给行动,那会起作用吗?
  • 所以如果我需要使用 rtbOutput.AppendText(fields[0].TrimStart().TrimEnd().ToString() + " Email Profile set.\n")
  • @user1158745 应该可以,您可以将该行放在匿名函数中,但如果您还想传递参数,那么修改扩展方法签名很简单。
  • 抱歉什么意思?你能给我一个使用附加文本的例子吗?
  • @user1158745 你拿你那里的例子,你把它放在他的// Code to run on main thread here 所在的地方。你什么都没有改变。它有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-19
  • 2011-05-13
  • 2015-02-20
相关资源
最近更新 更多