C# 创建MethodInvoker函数

C# 创建MethodInvoker函数,c#,methods,delegates,C#,Methods,Delegates,因此,我有多线程的应用程序。我遇到了这个错误“Cross thread operation not valid:从创建控件的线程以外的线程访问控件” 我的线程正在调用windows窗体控件。所以我用了 Invoke(新的MethodInvoker(委托{ControlsAction;})) 我正试图找出一种方法,使这个通用方法,这样我可以重用代码,使应用程序更干净 例如,在我的调用中,我使用一个富文本框执行以下操作 rtbOutput.Invoke(new MethodInvoker(deleg

因此,我有多线程的应用程序。我遇到了这个错误“Cross thread operation not valid:从创建控件的线程以外的线程访问控件”

我的线程正在调用windows窗体控件。所以我用了

Invoke(新的MethodInvoker(委托{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这样的东西,它似乎不喜欢。

像这样的东西应该可以解决这个问题:

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

使用动作代替/与委托一起使用。确定动作动作。如果它包含文本或类似的内容呢。如果我将其传递到act中,这会起作用吗?因此,如果我需要使用rtbOutput.AppendText(字段[0].TrimStart().TrimEnd().ToString()+“电子邮件配置文件集。\n”)@user1158745它应该起作用,您可以将该行放在匿名函数中,但是,如果您想同时传递参数,那么只需修改扩展方法签名即可。对不起,这是什么意思?你能给我一个使用追加文本的例子吗?@user1158745你拿你那里的例子,把它放在主线程上运行的代码所在的地方。你什么也没改变。它起作用了。