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
355 views
in Technique[技术] by (71.8m points)

c# - Is there default way to get first task that finished successfully?

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

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

1 Reply

0 votes
by (71.8m points)

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

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

...