4

我正试图把头绕在 RX 周围,但我的大脑在某个地方爆炸了 :)

我想要做的是通过 RX 以异步方式调用 WCF 方法。这里没什么特别的,但是当 WCF 方法抛出错误时,我想重新创建通道并再试一次(最多 3 次)。

到目前为止,我所拥有的是:

var _sc = new Service.Service1Client();
var _observableFunc = Observable.FromAsyncPattern<int, string>(_sc.BeginGetData, _sc.EndGetData);
var _observable = _observableFunc(666);

var _defered = Observable.Defer(() => _observable);

// Here something should be done, but don't know what...

using (_retryable.Subscribe(x => Console.WriteLine("Async ==> '{0}'", x),
                            ex => Console.WriteLine("Oops ==> {0}", ex.Message)))
{
    Console.ReadLine();
}

我玩弄了Catch<TSource, TException>,这让我可以捕获异常并继续使用相同的 observable,从而给了我想要的东西。唯一的问题是它永远运行,这意味着如果我继续抛出异常,事情就永远不会停止!

4

1 回答 1

3

Try doing this:

var retryable = Observable.Defer(() => _observableFunc(666).Retry(3));

The Retry extension method "Repeats the source observable sequence the specified number of times or until it successfully terminates."

Also, don't do this:

var _observable = _observableFunc(666);
var _defered = Observable.Defer(() => _observable);

There's no point deferring the observable after you've kicked it off.

You should do this instead:

var _defered = Observable.Defer(() => _observableFunc(666));

Then you're only one step away from my suggested solution at the top.

于 2012-09-19T00:31:23.420 回答