gpt4 book ai didi

c# - MethodInvoker + lambda + arguments + 跨线程操作

转载 作者:行者123 更新时间:2023-11-30 21:15:24 27 4
gpt4 key购买 nike

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

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

这工作正常。

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

我想这样做:

        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.
}

最佳答案

如果这是您的常见场景,我建议编写一个扩展方法:

public static class ControlExtensions
{
public static void EnsureInvokeAsync(this Control control, Action action)
{
if (control.InvokeRequired) control.BeginInvoke(action);
else action();
}
}

class MyControl : UserControl
{
void M(string s)
{
// the lambda will capture the string in a closure
// the compiler does all the hard work for you
this.EnsureInvokeAsync(() => _button.Text = s);
}
}

此外,您应该考虑使用 BackgroundWorker 或任务进行异步操作。

关于c# - MethodInvoker + lambda + arguments + 跨线程操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5770665/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com