I have an IEnumerable sequence which contains some blocking network operations (replaced with some simple yields in the example code below). I am using Reactive Extensions to convert the stream of data coming across the network into an observable sequence.
I'm looking for a way to marshal the exceptions across to the main thread so that unhandled exceptions don't cause my application to terminate. I can't place try/catch blocks on the IEnumerable thread because the compiler does not permit yield return statements inside try/catch statements.
using System;
using System.Collections.Generic;
using System.Concurrency;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Main thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
var observable = TestEnumerable().ToObservable(Scheduler.NewThread); //Needs to be on a new thread because it contains long-running blocking operations
// Use subject because we need many subscriptions to a single data source
var subject = new Subject<int>();
subject.Subscribe(x => Console.WriteLine("Subscriber1: " + x + " on thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId),
x => Console.WriteLine("Subscriber1 ERROR: " + x+ " on thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId),
() => Console.WriteLine("Subscriber1 Finished"+ " on thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId));
subject.Subscribe(x => Console.WriteLine("Subscriber2: " + x + " on thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId),
x => Console.WriteLine("Subscriber2 ERROR: " + x+ " on thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId),
() => Console.WriteLine("Subscriber2 Finished"+ " on thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId));
Console.WriteLine("Press key to start receiving data");
Console.ReadKey();
开发者_JS百科 var sub = observable.Subscribe(subject);
Console.WriteLine("Press key to exit");
Console.ReadKey();
sub.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("Caught exception on main thread");
}
}
public static IEnumerable<int> TestEnumerable()
{
while (true)
{
yield return 1;
Thread.Sleep(200);
yield return 2;
Thread.Sleep(200);
yield return 3;
Thread.Sleep(200);
throw new InvalidOperationException();
}
}
}
}
The solution depends on whether you have Dispatcher / SynchronisationContext available to you. It is certainly preferable to use one in this scenario.
Solution 1: Dispatcher / SynchronisationContext is available
(ie. using WPF, Windows Forms, or a custom Dispatcher loop)
You can use ObserveOn
+ Catch
to move the error back onto the Dispatcher thread. I've seen this used in a WPF application and it worked well.
How you move your IScheduler
/ DispatcherScheduler
around is up to you (we used IoC)
public static IObservable<T> CatchOn<T>(this IObservable<T> source,
IScheduler scheduler)
{
return source.Catch<T,Exception>(ex =>
Observable.Throw<T>(ex).ObserveOn(scheduler));
}
// We didn't use it, but this overload could useful if the dispatcher is
// known at the time of execution, since it's an optimised path
public static IObservable<T> CatchOn<T>(this IObservable<T> source,
DispatcherScheduler scheduler)
{
return source.Catch<T,Exception>(ex =>
Observable.Throw<T>(ex).ObserveOn(scheduler));
}
Solution 2: No Dispatcher available
Instead of using Console.ReadKey()
, use a ManualResetEvent
and wait on it, then throw the mutable error afterwards:
static void Main(string[] args)
{
try
{
Console.WriteLine("Main thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
var observable = TestEnumerable().ToObservable(Scheduler.NewThread); //Needs to be on a new thread because it contains long-running blocking operations
// Use subject because we need many subscriptions to a single data source
var subject = new Subject<int>();
Exception exception = null;
ManualResetEvent mre = new ManualResetEvent(false);
using(subject.Subscribe(
x => Console.WriteLine(x),
ex => { exception = ex; mre.Set(); },
() => Console.WriteLine("Subscriber2 Finished")))
using(subject.Subscribe(
x => Console.WriteLine(x),
ex => { exception = ex; mre.Set(); },
() => Console.WriteLine("Subscriber2 Finished")))
using (observable.Subscribe(subject))
{
mre.WaitOne();
}
if (exception != null)
throw exception;
}
catch (Exception ex)
{
Console.WriteLine("Caught exception on main thread");
}
}
精彩评论