将方法传递给背景工dowork [英] Passing a method to a backgroundworker dowork
本文介绍了将方法传递给背景工dowork的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的代码中,有一种方法可以像过去总是订阅updateWorker_DoWork方法一样,将其传递给这样的方法
In the code below, is there a way to instead of always subscribing the updateWorker_DoWork method, pass it a method like this
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()
中将对象强制转换回此特定类型并调用它即可.
For your RunWorkerAsync()
you can pass any argument you like. You can just put a Func()
or Action()
into it and in your DoWork()
you just cast the object back to this specific type and call it.
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";
}
这篇关于将方法传递给背景工dowork的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文