Task.WhenAny specific result?

Status
Not open for further replies.
Hi,

I have the following problem:

I have three servers, some may be down and some may reply but won't have the file I am looking for there might also be one that replies which has the file I am looking for.
This request runs async because otherwise I'll be waiting the TCP timeout (21 sec iirc ) before the other one gets run.

I have used Task.WhenAny for this and it works great if no other server replies because it will timeout and the server which has the file will be the fastest to reply.

Now comes my problem, servers which may not have the file may still reply faster than the one which does have the file making a Null result the fastest result even though there is a reply coming with the file that I want.

Can I use the Task result to filter out the ones i don't want and keep waiting for other results? Stopping when i have what i want?

It is not immediately clear how to this with the Task construct.
 
So I finally got around to implementing this. I came up with the following using RX:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reactive;
using System.Threading;
using System.Reactive.Linq;

namespace rxTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var program = new Program();
            program.Run();
        }

        public void Run()
        {

            var s1 = Observable.ToAsync<string>(Wrong)();
            var s2 = Observable.ToAsync<string>(Wronger)();
            var s3 = Observable.ToAsync<string>(Right)();
            var s4 = Observable.ToAsync<string>(Righter)();
            s3.Merge(s2).Merge(s1).Merge(s4).Where(x => x.Equals("right")).Take(1).Subscribe(Console.WriteLine);
            Console.ReadLine();
        }

        public string Wrong()
        {
            Thread.Sleep(400);
            Console.WriteLine("Wrong");
            return "wrong";
        }

        public string Right()
        {
            Thread.Sleep(3000);
            Console.WriteLine("Rightoooo");
            return "right";
        }

        public string Wronger()
        {
            Thread.Sleep(500);
            Console.WriteLine("Wronger");
            return "wronger";
        }

        public string Righter()
        {
            Thread.Sleep(700);
            Console.WriteLine("Wronger");
            return "right";
        }
    }
}

It does what I want in 5 lines of code. The Thread.Sleep's will be converted to HTTP requests but I guess the setup will work for that as well.

Thanks.

Any pointers about things I need to keep in mind when using RX, please share :)
 
Status
Not open for further replies.