gpt4 book ai didi

c# - 将方法传递给 backgroundworker dowork

转载 作者:行者123 更新时间:2023-11-30 14:42:03 24 4
gpt4 key购买 nike

在下面的代码中,有没有一种方法可以不总是订阅 updateWorker_DoWork 方法,而是将它传递给这样的方法

public void GetUpdates(SomeObject blah)
{
//...
updateWorker.DoWork += new DoWorkEventHandler(blah);
//...
}


public void GetUpdates()
{
//Set up worker
updateWorker.WorkerReportsProgress = true;
updateWorker.WorkerSupportsCancellation = true;
updateWorker.DoWork += new DoWorkEventHandler(updateWorker_DoWork);
updateWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(updateWorker_RunWorkerCompleted);
updateWorker.ProgressChanged +=
new ProgressChangedEventHandler(updateWorker_ProgressChanged);

//Run worker
_canCancelWorker = true;
updateWorker.RunWorkerAsync();
//Initial Progress zero percent event
_thes.UpdateProgress(0);
}

最佳答案

对于您的 RunWorkerAsync(),您可以传递任何您喜欢的参数。您只需将 Func()Action() 放入其中,然后在您的 DoWork() 中将对象转换回此特定输入并调用它。

例子是 herehere .

private void InitializeBackgroundWorker()
{
_Worker = new BackgroundWorker();

// On a call cast the e.Argument to a Func<TResult> and call it...
// Take the result from it and put it into e.Result
_Worker.DoWork += (sender, e) => e.Result = ((Func<string>)e.Argument)();

// Take the e.Result and print it out
// (cause we will always call a Func<string> the e.Result must always be a string)
_Worker.RunWorkerCompleted += (sender, e) =>
{
Debug.Print((string)e.Result);
};
}

private void StartTheWorker()
{
int someValue = 42;

//Take a method with a parameter and put it into another func with no parameter
//This is called currying or binding
StartTheWorker(new Func<string>(() => DoSomething(someValue)));

while(_Worker.IsBusy)
Thread.Sleep(1);

//If your function exactly matches, just put it into the argument.
StartTheWorker(AnotherTask);
}

private void StartTheWorker(Func<string> func)
{
_Worker.RunWorkerAsync(func);
}

private string DoSomething(int value)
{
return value.ToString("x");
}

private string AnotherTask()
{
return "Hello World";
}

关于c# - 将方法传递给 backgroundworker dowork,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3475263/

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