开发者

How to manage a Webservice timeout in System.Reactive

I am starting out with System.R开发者_开发技巧eactive and loving the simplicity of it but I have come up against something which seems it must have an elegant solution but I am not creating anything like an elegant solution!!

The scenario is that I want to go off to a 3rd party web service to get some information (in a separate thread) and at the same time search locally. Then merge the results UNLESS the webservice times out and I will take only the information from the local results.

Therefore I want to introduce a timeout to the Observable section in here:

using System;
using System.Linq;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting");
            var o = Observable.Start(DoSeparateThreadCall);

            DoCallInThisThread();

            o.First();

            Console.WriteLine("the End");
            Console.ReadLine();
        }

        private static void DoSeparateThreadCall()
        {
            Console.WriteLine("Started in separate thread call");
            Thread.Sleep(3000);
            Console.WriteLine("Ended in separate thread call");
        }

        static void DoCallInThisThread()
        {
            Console.WriteLine("Started in this thread call");
            Thread.Sleep(2000);
            Console.WriteLine("Ended in this thread call");
        }
    }
}

Anyone done anything similar? It seems like it must be a reasonably common thing to do, i.e. if the 3rd party call times out do X?


Regardless on how you want to want the timeout to occur (Rx controlled or client proxy), you probably want to use Catch:

public IObservable<IList<SearchResult>> GetSearchResults()
{
    return Observable.ForkJoin(
        GetRemoteSearchResults(),
        GetLocalSearchResults()
        )
        .Select(MergeSearchResults);
}

private IObservable<IList<SearchResult>> GetRemoteSearchResults()
{
    return GetSearchResultsFromWebService()
        .Timeout(RemoteTimeOut)
        .Catch<IList<SearchResult>, TimeoutException>(
            Observable.Return((IList<SearchResult>)new List<SearchResult>())
        );
}

private IObservable<IList<SearchResult>> MergeSearchResults(
    IList<SearchResult>[] allResults)
{
    var localResults = allResults[0];
    var remoteResults = allResults[1];

    if (remoteResults.Count == 0)
    {
        return localResults;
    }
    else
    {
        var mergedResults = new List<SearchResult>();
        // merge

        return mergedResults;
    }
}

If you want to use your webservice's timeout, just catch that exception type instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜