Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4012780
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T09:17:24+00:00 2026-05-20T09:17:24+00:00

I have an IEnumerable sequence which contains some blocking network operations (replaced with some

  • 0

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();
                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();
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T09:17:24+00:00Added an answer on May 20, 2026 at 9:17 am

    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");
                }
    
            }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an IEnumerable collection, which is hierarchical in that one element contains several
I have a C# class which needs to process a sequence of items (
I have a simple table: ID | Value When I do this: var sequence
I have the following code that uses Sequence objects to read data from a
A method returns a sequence, IEnumerable<T> , and you now want to check if
I have a linq to sql database. Very simplified we have 3 tables, Projects
I want to do a search for Music instruments which has its informations Name,
I have recently been in a situation where I needed to perform an operation
I have several huge sorted enumerable sequences that I want to merge . Theses
Lets say I have something called Stuff in my database, with a property called

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.