Waiting for a single task from the <Task <.. >> list to be cleaner, perhaps using LINQ?

In my application, I have List<Task<Boolean>>which I am Task.Wait[..]on to determine if they are successfully executed ( Result = true). Although if during my wait it Taskcompletes and returns false, I want to cancel all the others Taskthat I am waiting for and will do something based on this.

I created two ugly methods for this

// Create a CancellationToken and List<Task<..>> to work with
CancellationToken myCToken = new CancellationToken();
List<Task<Boolean>> myTaskList = new List<Task<Boolean>>();

//-- Method 1 --
    // Wait for one of the Tasks to complete and get its result
Boolean finishedTaskResult = myTaskList[Task.WaitAny(myTaskList.ToArray(), myCToken)].Result;

    // Continue waiting for Tasks to complete until there are none left or one returns false
    while (myTaskList.Count > 0 && finishedTaskResult)
    {
        // Wait for the next Task to complete
        finishedTaskResult = myTaskList[Task.WaitAny(myTaskList.ToArray(), myCToken)].Result;
        if (!finishedTaskResult) break;
    }
    // Act on finishTaskResult here

// -- Method 2 -- 
    // Create a label to 
    WaitForOneCompletion:
    int completedTaskIndex = Task.WaitAny(myTaskList.ToArray(), myCToken);

    if (myTaskList[completedTaskIndex].Result)
    {
        myTaskList.RemoveAt(completedTaskIndex);
        goto WaitForOneCompletion;
    }
    else
        ;// One task has failed to completed, handle appropriately 

I was wondering if there is a cleaner way to do this, possibly with LINQ?

+1
source share
3 answers

, , :

public static IEnumerable<Task<T>> Order<T>(this IEnumerable<Task<T>> tasks)
{
    var taskList = tasks.ToList();

    var taskSources = new BlockingCollection<TaskCompletionSource<T>>();

    var taskSourceList = new List<TaskCompletionSource<T>>(taskList.Count);
    foreach (var task in taskList)
    {
        var newSource = new TaskCompletionSource<T>();
        taskSources.Add(newSource);
        taskSourceList.Add(newSource);

        task.ContinueWith(t =>
        {
            var source = taskSources.Take();

            if (t.IsCanceled)
                source.TrySetCanceled();
            else if (t.IsFaulted)
                source.TrySetException(t.Exception.InnerExceptions);
            else if (t.IsCompleted)
                source.TrySetResult(t.Result);
        }, CancellationToken.None, TaskContinuationOptions.PreferFairness, TaskScheduler.Default);
    }

    return taskSourceList.Select(tcs => tcs.Task);
}

, , , :

foreach(var task in myTaskList.Order())
    if(!await task)
        cancellationTokenSource.Cancel();
+1

Task.WhenAny, , .

Task, , - , .

- :

static class TasksExtensions
{
    public static Task<Task<T>> WhenAny<T>(this IList<Task<T>> tasks, Func<T, bool> filter)
    {
        CompleteOnInvokePromiseFilter<T> action = new CompleteOnInvokePromiseFilter<T>(filter);

        bool flag = false;
        for (int i = 0; i < tasks.Count; i++)
        {
            Task<T> completingTask = tasks[i];

            if (!flag)
            {
                if (action.IsCompleted) flag = true;
                else if (completingTask.IsCompleted)
                {
                    action.Invoke(completingTask);
                    flag = true;
                }
                else completingTask.ContinueWith(t =>
                {
                    action.Invoke(t);
                });
            }
        }

        return action.Task;
    }
}

class CompleteOnInvokePromiseFilter<T>
{
    private int firstTaskAlreadyCompleted;
    private TaskCompletionSource<Task<T>> source;
    private Func<T, bool> filter;

    public CompleteOnInvokePromiseFilter(Func<T, bool> filter)
    {
        this.filter = filter;
        source = new TaskCompletionSource<Task<T>>();
    }

    public void Invoke(Task<T> completingTask)
    {
        if (completingTask.Status == TaskStatus.RanToCompletion && 
            filter(completingTask.Result) && 
            Interlocked.CompareExchange(ref firstTaskAlreadyCompleted, 1, 0) == 0)
        {
            source.TrySetResult(completingTask);
        }
    }

    public Task<Task<T>> Task { get { return source.Task; } }

    public bool IsCompleted { get { return source.Task.IsCompleted; } }
}

:

List<Task<int>> tasks = new List<Task<int>>();    
...Initialize Tasks...

var task = await tasks.WhenAny(x => x % 2 == 0);

//In your case would be something like tasks.WhenAny(b => b);
+1

Jon Skeet, Stephen Toub , " ".

, , -.

, false. , ( " " ), ( " " ).

, " ", , :

public async Task DoWorkAndCancel(Func<CancellationToken, Task<bool>> work,
    CancellationTokenSource cts)
{
  if (!await work(cts.Token))
    cts.Cancel();
}

List<Func<CancellationToken, Task<bool>>> allWork = ...;
var cts = new CancellationTokenSource();
var tasks = allWork.Select(x => DoWorkAndCancel(x, cts));
await Task.WhenAll(tasks);
+1

Source: https://habr.com/ru/post/1657677/


All Articles