gpt4 book ai didi

c# - 接受多个参数的 BackgroundWorker 的替代方案?

转载 作者:IT王子 更新时间:2023-10-29 04:07:34 26 4
gpt4 key购买 nike

BackgroundWorker 对象允许我们将单个参数传递给 DoWorkEventHandler。

// setup/init:
BackgroundWorker endCallWorker = new BackgroundWorker();
endCallWorker.DoWork += new DoWorkEventHandler(EndCallWorker_DoWork);
...
endCallWorker.RunWorkerAsync(userName);

// the handler:
private void EndCallWorker_DoWork(object sender, DoWorkEventArgs e)
{
string userName = e.Argument as string;
...
}

要传递多个参数,我必须将它们包装在一个对象中,就像这个糟糕的字符串数组:

// setup/init:

BackgroundWorker startCallWorker = new BackgroundWorker();
startCallWorker.DoWork += new DoWorkEventHandler(StartCallWorker_DoWork);
...
startCallWorker.RunWorkerAsync(new string[]{userName, targetNumber});


// the handler:
private void StartCallWorker_DoWork(object sender, DoWorkEventArgs e)
{
string[] args = e.Argument as string[];
string userName = args[0];
string targetNumber = args[1];
}

是否有另一个对象或模式允许我们很好地传递多个参数,或者理想情况下,编写我们自己的签名?

最佳答案

您可以使用闭包 (Lambda):

backgroundWorker.DoWork += (s, e) => MyWorkMethod(userName, targetNumber);

或者用委托(delegate)(匿名方法)语法:

backgroundWorker.DoWork += 
delegate(object sender, DoWorkEventArgs e)
{
MyWorkMethod(userName, targetNumber);
};

关于c# - 接受多个参数的 BackgroundWorker 的替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1145780/

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