Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

c# - Waiting for a single task to fail out of a List<Task<..>> more cleanly, possibly with LINQ?

In my application I have a List<Task<Boolean>> that I Task.Wait[..] on to determine if they completed successfully (Result = true). Though if during my waiting a Task completes and returns a falsey value I want to cancel all other Task I am waiting on and do something based on this.

I have created two "ugly" methods to do 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 was a cleaner way to do this, possibly with LINQ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the following method to take a sequence of tasks and create a new sequence of tasks that represents the initial tasks but returned in the order that they all complete:

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);
}

Now that you have the ability to order the tasks based on their completion you can write the code basically exactly as your requirements dictate:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...