如何抽象方法的调用
我有一个用户可以执行的任务列表。每个都需要一些时间,因此它们应该在后台线程上运行并向 UI 线程报告其进度。
我的问题是如何以某种抽象的方式实现这一点(没有大的开关)。
我现在拥有的是类 Task
public class Task {
public string Name { get; set; }
public ??? Action { get; set; } // Doesn't compile
}
A ListBox,其中包含所有任务,这些任务将在 SelectionChanged 上绘制代表任务 (TaskUC) 的 UserControl。此 UserControl 有一个执行事件 ( TaskUC.Execute += TaskExecute
),当用户想要执行任务时会触发该事件。
我的问题就在这里。在 TaskExecute 方法上,我想初始化一个 BackgroundWorker,其中 DoWork 处理程序应在 Task.Action 中定义。像这样的事情:
private void TaskExecute(object sender, RoutedEventArgs e) {
Task task = (Task) e.OriginalSource;
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.RunWorkerCompleted += WorkerRunWorkerCompleted;
worker.DoWork += task.Action; // Doesn't compile
worker.RunWorkerAsync();
}
在处理 TaskExecute 的同一个类上有处理每个任务的方法。
private void Task1(object sender, DoWorkEventArgs e) {}
因此,如果用户选择第一个任务,我需要将 Task.Action 映射到 Task1 方法。
I have a List of Tasks that a user can preform. Each one will take some time so they should be running on a background thread and reporting their progress to the UI thread.
My problem is how to achieve this in an somehow abstract way (without a big switch).
What I have now is the class Task
public class Task {
public string Name { get; set; }
public ??? Action { get; set; } // Doesn't compile
}
A ListBox with all the tasks that will draw a UserControl representing the Task (TaskUC) on SelectionChanged. This UserControl has an Execute Event ( TaskUC.Execute += TaskExecute
) that triggers when a user wants to Execute the task.
My problem is here. On the TaskExecute method I want to initialize a BackgroundWorker where the DoWork Handler should be defined in the Task.Action. Something like this:
private void TaskExecute(object sender, RoutedEventArgs e) {
Task task = (Task) e.OriginalSource;
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.RunWorkerCompleted += WorkerRunWorkerCompleted;
worker.DoWork += task.Action; // Doesn't compile
worker.RunWorkerAsync();
}
And on the same class that handles the TaskExecute have the methods to handle each task.
private void Task1(object sender, DoWorkEventArgs e) {}
So in case the user choose the first task, I need to map Task.Action to Task1 method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DoWork
事件是一个DoWorkEventHandler
。要向此事件添加委托,它的类型必须是
DoWorkEventHandler
。The
DoWork
event is aDoWorkEventHandler
.To add a delegate to this event, it must be of type
DoWorkEventHandler
.我的建议是不要重新发明
任务
。使用Task
来封装您要查找的所有内容。请查看此处。
但就答案而言,SLAks的答案是正确的。
My suggestion is to not reinventing
Task
. UseTask<T>
which encapsulates all what you are looking for.Have a look here.
But for an answer, SLaks answer is correct.