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.
The
DoWorkevent is aDoWorkEventHandler.To add a delegate to this event, it must be of type
DoWorkEventHandler.