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

c# - TPL wait for task to complete with a specific return value

I'd like to make a request to X different web services who will each return either true or false.

These tasks should be executed in parallel and I'd like to wait for the first one that completes with a true value. When I receive a true value, I do not wish to wait for the other tasks to complete.

In the example below, t1 should not be awaited since t3 completes first and returns true:

var t1 = Task.Run<bool>(() =>
{
    Thread.Sleep(5000);
    Console.WriteLine("Task 1 Excecuted");
    return true;
}, cts.Token);

var t2 = Task.Run<bool>(() =>
{
    Console.WriteLine("Task 2 Executed");
    return false;
}, cts.Token);

var t3 = Task.Run<bool>(() =>
{
    Thread.Sleep(2000);
    Console.WriteLine("Task 3 Executed");
    return true;
}, cts.Token);

Essentially I'm looking for Task.WhenAny with a predicate, which of course doesn't exist.

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 simply use Task.WhenAny and a predicate multiple times until the "right" task comes along

async Task<T> WhenAny<T>(IEnumerable<Task<T>> tasks, Func<T, bool> predicate)
{
    var taskList = tasks.ToList();
    Task<T> completedTask = null;
    do
    {
        completedTask = await Task.WhenAny(taskList);
        taskList.Remove(completedTask);
    } while (!predicate(await completedTask) && taskList.Any());

    return completedTask == null ? default(T) : await completedTask;
}

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

...