简体   繁体   中英

Reporting Progress from Tasks

Is there a way to know the status of individual Task while using the WhenAll() or WaitAll() methods of Task.
When I use await Task.WhenAll(tasks.ToArray()) for every task that completes I would like to know that the task has completed.

There is probably a much nicer way to do this, but here is a raw class which takes an array of unstarted tasks and fires an event each time some of the tasks completes execution:

public class TaskBatchRunner
{
    private Task[] _tasks;

    public event EventHandler<Task> TaskCompleted;

    public TaskBatchRunner(Task[] tasks)
    {
        _tasks = tasks.Select(t =>
            new Task(() =>
            {
                t.ContinueWith(OnTaskCompleted);
                t.Start();
            })).ToArray();
    }

    public void Run()
    {
        foreach (var t in _tasks) t.Start();
        Task.WaitAll(_tasks);
    }

    private void OnTaskCompleted(Task completedTask)
    {
        TaskCompleted?.Invoke(this, completedTask);
    }
}

Usage:

        var taskRunner = new TaskBatchRunner(tasks.ToArray());
        taskRunner.TaskCompleted += MyTaskCompleted;
        taskRunner.Run();
        ...

    private void MyTaskCompleted(object sender, Task e)
    {
        System.Diagnostics.Debug.WriteLine($"task {e.Id} completed!");
    }

To report progress from an async or concurrent process use the IProgress<T> abstraction. Using the Progress<T> implmentation you can easily capture the current context and run your progress update / completion expression on the ui context while doing your work in the background:

public class WorkItem {
    public async Task DoWork(IProgress<bool> completionNotification) {
        await Task.Delay(TimeSpan.FromSeconds(2));
        //Work Done
        completionNotification.Report(true);
    }

    //Get, Set, Fire Property change etc
    public bool Completed {
        get; set;
    }
}

public class ViewModel {
    public async void ButtonClickHandler(object sender, EventArgs e) {
        var workitemTasks = WorkItems.Select(workItem =>
            workItem.DoWork(new Progress<bool>(done => workItem.Completed = done)))
            .ToList();
        await Task.WhenAll(workitemTasks);
    }

    //Get, Set, Fire Property change etc
    public IEnumerable<WorkItem> WorkItems {
        get; set;
    }
}

More Info

Reporting Progress From Async Tasks @StephenCleary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM