在下面的代码中,有没有办法代替总是订阅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);
}
答案 0 :(得分:3)
对于你的RunWorkerAsync()
,你可以传递任何你喜欢的论点。您只需将Func()
或Action()
放入其中,然后在DoWork()
中将对象强制转换回此特定类型并调用它。
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";
}
答案 1 :(得分:2)
如果我没有误解你,你需要lambda表达式来构造匿名方法。
updateWorker.DoWork += (sender,e)=>
{
//bla
}
现在您无需总是编写方法并将其传递给new DoWorkEventHandler(myMethod)
答案 2 :(得分:1)
解决了它,比我想的更简单。只需要为DoWork上调用的方法创建一个委托。可能应该更好地表达我原来的问题。
public delegate void DoWorkDelegate(object sender,DoWorkEventArgs e);
public void GetUpdates()
{
StartWorker(new DoWorkDelegate(updateWorker_DoWork));
}
public void StartWorker(DoWorkDelegate task)
{
//Set up worker
updateWorker.WorkerReportsProgress = true;
updateWorker.WorkerSupportsCancellation = true;
updateWorker.DoWork += new DoWorkEventHandler(task);
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);
}
private void updateWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = GetUpdatesTask(worker, e);
}