Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Lets say that i have a couple of tasks:

void Sample(IEnumerable<int> someInts)
{
    var taskList = someInts.Select(x => DownloadSomeString(x));
}

async Task<string> DownloadSomeString(int x) {...}

I want to to get the result of first successful task. So, the basic solution is to write something like:

var taskList = someInts.Select(x => DownloadSomeString(x));
string content = string.Empty;
Task<string> firstOne = null;
while (string.IsNullOrWhiteSpace(content)){
    try
    {
        firstOne = await Task.WhenAny(taskList);
        if (firstOne.Status != TaskStatus.RanToCompletion)
        {
            taskList = taskList.Where(x => x != firstOne);
            continue;
        }
        content = await firstOne;
    }
    catch(...){taskList = taskList.Where(x => x != firstOne);}
}

But this solution seems to run N+(N-1)+..+K tasks. Where N is someInts.Count and K is position of first successful task in tasks, so as it's rerunning all task except one that is captured by WhenAny. So, is there any way to get first task that finished successfully with running maximum of N tasks? (if successful task will be the last one)

See Question&Answers more detail:os

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

1 Answer

All you need to do is create a TaskCompletionSource, add a continuation to each of your tasks, and set it when the first one finished successfully:

public static Task<T> FirstSuccessfulTask<T>(IEnumerable<Task<T>> tasks)
{
    var taskList = tasks.ToList();
    var tcs = new TaskCompletionSource<T>();
    int remainingTasks = taskList.Count;
    foreach (var task in taskList)
    {
        task.ContinueWith(t =>
            {
                if (task.Status == TaskStatus.RanToCompletion)
                    tcs.TrySetResult(t.Result);
                else
                if (Interlocked.Decrement(ref remainingTasks) == 0)
                    tcs.SetException(new AggregateException(tasks.SelectMany(t1 => t1.Exception.InnerExceptions)));
            });
    }
    return tcs.Task;
}

And a version for tasks without a result:

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

    var tcs = new TaskCompletionSource<bool>();

    int remainingTasks = taskList.Count;

    foreach (var task in taskList)
    {
        task.ContinueWith(t =>
        {
            if (task.Status == TaskStatus.RanToCompletion)
                tcs.TrySetResult(true);
            else
                if (Interlocked.Decrement(ref remainingTasks) == 0)
                tcs.SetException(new AggregateException(
                    tasks.SelectMany(t1 => t1.Exception.InnerExceptions)));
        });
    }

    return tcs.Task;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...