MethodInvoker + lambda +参数+ CrossThread操作 [英] MethodInvoker + lambda + arguments + CrossThread Operation

查看:63
本文介绍了MethodInvoker + lambda +参数+ CrossThread操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用它来更改其他线程上的内容:

I'm using this to change something on other thread:

        MethodInvoker m = () => { login_submit.Text = "Login"; };
        if (InvokeRequired)
        {
            BeginInvoke(m);
        }
        else
        {
            Invoke(m);
        }

这很好.

如何将参数传递给该lamba表达式?

How can I pass argumets to that lamba expression?

我想那样做:

        MethodInvoker m = (string txt) => { login_submit.Text = txt; };
        if (InvokeRequired)
        {
            BeginInvoke(m); // I need to pass txt string in some way here.
        }
        else
        {
            Invoke(m); // I need to pass txt string in some way here.
        }

推荐答案

如果InvokeRequired为false,那么您根本不必担心调用任何东西-您已经在正确的线程上.

If InvokeRequired is false then you don't need to worry about invoking anything at all - you're already on the right thread.

更好的解决方案可能是这样的:

A better solution might be something like this:

public delegate void InvokerDelegate(string data);
public void DoStuff(string data){
  login_submit.Text = data;
}

,然后在调用它时执行:

and then when calling it do:

if (InvokeRequired){
  Invoke(InvokerDelegate(DoStuff), "something");
}
else{
  DoStuff("Something");
}

您将看到的一种相当常见的模式是对在多线程环境中操纵GUI的函数执行类似的操作

A fairly common pattern you will see is to do something like this for functions that manipulate the GUI in a multithreaded environment

public delegate void InvokerDelegate();
public void DoGuiStuff(){
  if (login_submit.InvokeRequired){
    login_submit.Invoke(InvokerDelegate(DoGuiStuff));
    return;  
  }

  login_submit.Text = "Some value";
}

如果使用上述模式,该函数将检查是否需要调用,如果需要,则在正确的线程上调用自身.然后返回.当它自身进行调用时,检查是否需要进行调用的检查返回false,因此它不会再次调用自身-它只运行代码.

If you use the above pattern the function checks to see if an invoke is required and if so Invokes itself on the right thread. It then returns. When it invokes itself the check to see if an invoke is required returns false so it doesn't bother invoking itself again - it just runs the code.

我只是回到了winforms,试图使用该模式只是花了一些令人沮丧的时间,试图弄清楚为什么我不能调用lambda.我以为最好再返回并更新此答案,以添加所需的演员表,以防其他人尝试使用它.

I just went back to winforms and tried to use that pattern only to spend a couple of frustrating minutes trying to work out why I couldn't invoke a lambda. I thought I'd better come back and update this answer to add the required casting in case anyone else tried to use it.

这篇关于MethodInvoker + lambda +参数+ CrossThread操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆