将方法传递给后台工作者 dowork
在下面的代码中,有没有一种方法可以不总是订阅 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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于您的
RunWorkerAsync()
,您可以传递您喜欢的任何参数。您只需将Func()
或Action()
放入其中,然后在DoWork()
中将对象强制转换回此特定的输入并调用它。示例如下此处 和此处。
For your
RunWorkerAsync()
you can pass any argument you like. You can just put aFunc()
orAction()
into it and in yourDoWork()
you just cast the object back to this specific type and call it.Examples are here and here.
如果我没有理解错的话,你需要 lambda 表达式来构造匿名方法。
现在您不必总是编写一个方法并将其传递给
new DoWorkEventHandler(myMethod)
If I didn't misunderstand you, you need lambda expressions to construct anonymous method.
Now you needn't always to write a method and pass it to
new DoWorkEventHandler(myMethod)
解决了,比我想象的要简单得多。只需为 DoWork 上调用的方法创建一个委托即可。也许应该更好地表达我原来的问题。
Worked it out, was way simpler than I was thinking. Just had to make a delegate for the method called on DoWork. Probably should have phrased my original question better.