I'm following on with a tutorial detailing handling events thrown in multiple subscribers to an event. However when the code is run, the TargetInvocationException catch block isn't catching the exceptions thrown in the method body of the subscribers: throw new Exception("Hello") and throw new Exception("World") respectively.
Instead I get an unhandled exception error in the first listener, predictably at throw new Exception("Hello") in private static void AlarmListener.
What is it that I'm doing incorrectly when attempting to catch the invoked method's exceptions?
class AggregatingExceptions
{
public void Main()
{
//create the alarm
AlarmAndLocation alarm = new AlarmAndLocation();
//subscribe the listeners
alarm.OnAlarmRaised += AlarmListener;
alarm.OnAlarmRaised += AlarmListener2;
try
{
alarm.RaiseAlarm("Kitchen");
}
catch (AggregateException agg)
{
foreach (Exception ex in agg.InnerExceptions)
{
Console.WriteLine(ex.Message);
}
}
}
private static void AlarmListener(object sender, AlarmEventArgs e)
{
Console.WriteLine("Alarm listener 1 called.");
throw new Exception("Hello");
}
private static void AlarmListener2(object sender, AlarmEventArgs e)
{
Console.WriteLine("Alarm listener 2 called.");
throw new Exception("World");
}
}
public class AlarmAndLocation
{
public event EventHandler<AlarmEventArgs> OnAlarmRaised = delegate { };
public List<Exception> exceptionList = new List<Exception>();
public void RaiseAlarm(string location)
{
foreach (Delegate handler in OnAlarmRaised.GetInvocationList())
{
try
{
handler.DynamicInvoke(this, new AlarmEventArgs(location));
}
catch (TargetInvocationException ex)
{
exceptionList.Add(ex.InnerException);
}
}
if(exceptionList.Count > 0)
{
throw new AggregateException(exceptionList);
}
}
}
public class AlarmEventArgs : EventArgs
{
public string Location { get; set; }
public AlarmEventArgs(string location)
{
Location = location;
}
}
Related
I have problems calling Form objects from another class.
In Form class I have this:
public void reloadMapOverlay(GMapOverlay overlay)
{
try
{
Invoke(new Action(() => this.map_Box.Overlays.Add(overlay)));
}
catch (Exception e)
{
Console.WriteLine("reloadMapOverlay: {0}", e);
this.setError("reloadMapOverlay: " + e);
}
}
And in another class (Map_custom.cs):
route.Points.Add(coords.get_position());
overlay.Routes.Add(route);
mainForm.reloadMapOverlay(overlay);
When mainForm.reloadMapOverlay executes, vb gives me and object in use an exception
System.InvalidOperationException
in overlay object.
What can I can do?
i try adding dispacher in mainForm, ->
public Dispatcher dispacher = Dispatcher.CurrentDispatcher;
public void reloadMapOverlay(GMapOverlay overlay)
{
try
{
dispacher.Invoke(new Action(() => this.map_Box.Overlays.Add(overlay)));
}
catch (Exception e)
{
Console.WriteLine("reloadMapOverlay: {0}", e);
this.setError("reloadMapOverlay: " + e);
}
}
and nothing.
i have
public void reloadMapOverlay(GMapOverlay overlay)
{
try
{
Invoke(new Action(() => this.map_Box.Overlays.Add(overlay)));
}
catch (Exception e)
{
Console.WriteLine("reloadMapOverlay: {0}", e);
this.setError("reloadMapOverlay: " + e);
}
} in mainForm,
then, in another class (Map_Custom.cs) i have a function
public void addRoute()
{
if (!coords.isWrongCoords())
{
Console.WriteLine("Route");
route.Points.Add(coords.get_position());
overlay.Routes.Add(route);
mainForm.reloadMapOverlay(overlay);
}
}
and in mainFrom i have a function (inside one thread) where i call
Thread addRoute = new Thread(new ThreadStart(map.addRoute));
addRoute.IsBackground = true;
addRoute.Start();
I am having a case where an exception thrown in UI thread doesn't get catched in the calling thread.
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows;
namespace SynchronisationContextAndExceptionWPF
{
public partial class MainWindow : Window
{
private readonly SynchronizationContext _synchronizationContext;
public MainWindow()
{
InitializeComponent();
_synchronizationContext = SynchronizationContext.Current;
}
private void Button_OnClick(object sender, RoutedEventArgs e)
{
try
{
_synchronizationContext.Send(
x =>
{
try
{
DoSomethingOnUiThreadThatThrowsException();
}
catch (Exception)
{
Debug.WriteLine("Catched Exception in thread that threw it.");
throw;
}
}, null);
}
catch (Exception)
{
Debug.WriteLine("Catched Exception in thread that calles Send-Method.");
throw;
}
}
private static void DoSomethingOnUiThreadThatThrowsException()
{
throw new Exception("Any Exception...");
}
}
}
First I thought that cannot possible (all documentation I found said that I can catch exceptions there).
After some reasearch I found the problem: My application uses an UnhandledExceptionHandler. That handles the DispatcherUnhandledException-Event. I am showing some information to the user and set e.Handled = true;:
using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;
namespace SynchronisationContextAndExceptionWPF
{
public partial class App : Application
{
public App()
{
DispatcherUnhandledException += App_DispatcherUnhandledException;
}
private static void App_DispatcherUnhandledException(
object sender,
DispatcherUnhandledExceptionEventArgs e)
{
Debug.WriteLine("Catched Exception in UnhandledExceptionHandler.");
// This line makes the difference:
e.Handled = true;
}
}
}
So the question: why is the DispatcherUnhandledException-Event raised even if I handle it?
How would you solve this situation?
If you have a lot of controls, you can generate a new class which remenbers the special exception variable. So you only need to change the initialization of your _synchronizationContext (hopefully only once at your base class of your controls).
public partial class MainWindow : Window
{
private readonly MySynchronizationContext _synchronizationContext;
public MainWindow()
{
InitializeComponent();
_synchronizationContext = new MySynchronizationContext(SynchronizationContext.Current);
}
private void button_Click(object sender, RoutedEventArgs e)
{
try
{
_synchronizationContext.Send(
x =>
{
DoSomethingOnUiThreadThatThrowsException();
}, null);
}
catch (Exception)
{
Debug.WriteLine("Catched Exception in thread that calles Send-Method.");
throw;
}
}
private static void DoSomethingOnUiThreadThatThrowsException()
{
throw new Exception("Any Exception...");
}
}
class MySynchronizationContext
{
SynchronizationContext innerContext;
public MySynchronizationContext(SynchronizationContext ctx)
{
innerContext = ctx;
}
public virtual void Send(SendOrPostCallback d, object state)
{
Exception threadException = null;
try
{
innerContext.Send(_ =>
{
try
{
d.Invoke(state);
}
catch (Exception exception)
{
threadException = exception;
}
}, null);
}
catch (Exception ex)
{
}
if (threadException != null)
{
throw new Exception("Synchronization error", threadException);
}
}
}
Inside your lambda expression you can set an Exception variable and check this variable later at the calling thread. If it was set, then throw exception at calling thread.
private void button_Click(object sender, RoutedEventArgs e)
{
Exception threadException = null;
try
{
_synchronizationContext.Send(
x =>
{
try
{
DoSomethingOnUiThreadThatThrowsException();
}
catch (Exception ex)
{
Debug.WriteLine("Catched Exception in thread that threw it.");
threadException = ex;
//throw; --> don't throw exception here; otherwise you will get DispatcherUnhandledException twice.
}
}, null);
}
catch (Exception)
{
Debug.WriteLine("Catched Exception in thread that calles Send-Method.");
throw;
}
if(threadException != null)
{
Debug.WriteLine("Catched Exception in thread that calles Send-Method.");
throw threadException; //throw you previously catched exception here.
}
}
Kind Regards,
Daniel
I have a wcf service, and the corresponding client. When service faulted every call from client to service throw a exception. But i need that client reconnect, so i wrap a client into exception handler with reconnection.
What is a prefer way to implement auto reconnect behavior?
My client:
internal sealed class BloombergClient
{
#region Singleton
private static Lazy<BloombergClient> instance = new Lazy<BloombergClient>(() => new BloombergClient(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
public static BloombergClient Instance { get { return instance.Value; } }
#endregion
private readonly ExceptionReconnectHandler exceptionHandler;
private readonly Object lockObject = new Object();
private readonly ManualResetEventSlim eventSlim = new ManualResetEventSlim(true);
private BloombergModuleServiceClient client;
private volatile Boolean isConnecting;
public event System.EventHandler ConnectionEstablished;
private BloombergClient()
{
this.exceptionHandler = new ExceptionReconnectHandler(HandleException);
Connect();
}
//Example method
public Double GetDailyClose(String bloombergTicker, DateTime date)
{
eventSlim.Wait();
return exceptionHandler.Execute(() => this.client.GetDailyClose(bloombergTicker, date));
}
private void HandleException(Exception e)
{
Connect();
}
private void BloombergServiceClientFaulted(object sender, EventArgs e)
{
Connect();
}
private Boolean CreateClient()
{
Boolean init = false;
if (this.client != null)
{
((ICommunicationObject)client).Faulted -= BloombergServiceClientFaulted;
((ICommunicationObject)client).Closed -= BloombergServiceClientFaulted;
}
this.client = new BloombergModuleServiceClient();
if (this.client.State == CommunicationState.Created)
{
((ICommunicationObject)client).Faulted += BloombergServiceClientFaulted;
((ICommunicationObject)client).Closed += BloombergServiceClientFaulted;
init = true;
}
else
{
init = false;
}
return init;
}
private void Connect()
{
lock (this.lockObject)
{
if (isConnecting) return;
lock (this.lockObject)
{
if (isConnecting) return;
isConnecting = true;
}
}
//if (eventSlim.IsSet) return; - offcourse not working
eventSlim.Reset();
try
{
while (true)
{
try
{
if (client != null && client.State == CommunicationState.Opened)
{
((ICommunicationObject)client).Abort();
}
if (CreateClient())
{
break;
}
}
catch (Exception e)
{
Log.Instance.WriteLineT(e.Message, "Bloomberg Client");
}
Thread.Sleep(1000);
}
}
finally
{
eventSlim.Set();
isConnecting = false;
ConnectionEstablished.Raise(this);
}
}
}
public class ExceptionReconnectHandler
{
private readonly Action<Exception> handler;
public ExceptionReconnectHandler(Action<Exception> handler)
{
if (handler == null) throw new ArgumentNullException("handler");
this.handler = handler;
}
public virtual T Execute<T>(Func<T> func)
{
if (func == null) throw new ArgumentNullException("func");
while (true)
{
try
{
return func();
}
catch (Exception e)
{
handler(e);
}
}
}
public virtual void Execute(Action action)
{
if (action == null) throw new ArgumentNullException("action");
while (true)
{
try
{
action();
return;
}
catch (Exception e)
{
handler(e);
}
}
}
}
I am using a singleton pattern for a global event manager class that is not handling exceptions in an acceptable manner.
If an exception is thrown in the code called by one of the events being executed, I always get a Exception has been thrown by the target of an invocation. error. This error contains no information related to the original exception, making it extremely difficult to debug any errors.
Is there some way to pass the original exception information back to the event manager?
public class ApplicationSettings
{
private static EventManager _manager = new EventManager();
public static EventManager EventManager
{
get { return _manager; }
}
}
The event manager class:
public class EventManager
{
public event EventHandler<ReportExecutionArgs> ExecuteReportCurrentPage;
public event EventHandler<ReportExecutionArgs> ExecuteReportNewPage;
public virtual void OnExecuteReportCurrentPage(object sender, ReportExecutionArgs e)
{
try
{
if (this.ExecuteReportCurrentPage != null)
this.ExecuteReportCurrentPage(sender, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public virtual void OnExecuteReportNewPage(object sender, ReportExecutionArgs e)
{
try
{
if (this.ExecuteReportNewPage != null)
this.ExecuteReportNewPage(sender, e);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
Some other class will handle these events
ApplicationSettings.EventManager.ExecuteReportNewPage += new EventHandler<ReportExecutionArgs>(reportOpenedNewPage);
private void reportOpenedNewPage(object sender, ReportExecutionArgs e)
{
//something in this code throws an error
LitePage page = new LitePage();
_tabs.AddPage(page);
Report report = setReport(page, e);
}
EDIT
Just to clarify, the try/catch blocks in the OnExecuteReport methods are not catching the exception.
A TargetInvocationException such as the one you describe will almost always have the originating exception in it's InnerException.
I'm trying to handle the Timer's exception. It would be nice if the class had something like HandlerExceptionEvent so that we could add some event to log something or stop the timer.
PS: I don't want to add a try/catch block inside ElapsedEventHandler().
class Program
{
static void Main(string[] args) {
System.Timers.Timer t = new System.Timers.Timer(1000);
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();
System.Threading.Thread.Sleep(10000);
t.Stop();
Console.WriteLine("\nDone.");
Console.ReadLine();
}
static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
Console.WriteLine("Ping!");
throw new Exception("Error!");
}
}
PS: I don't want to add "try/catch Exception" inside ElapsedEventHandler()
Since the Timer class doesn't support such an event how would you otherwise catch an exception?
If you insist on using the Timer class then perhaps this is your only option:
var t = new System.Timers.Timer(1000);
t.Elapsed += (sender, e) => {
try
{
t_Elapsed(sender, e);
}
catch (Exception ex)
{
// Error handling here...
}
};
This way the actual handler t_Elapsed doesn't contain any error handling and you can create a wrapper class for the Timer class that hides this implementation detail and in turn provides an event for exception handling.
Here's one way to do that:
class ExceptionHandlingTimer
{
public event Action<Exception> Error;
System.Timers.Timer t;
public ExceptionHandlingTimer(double interval)
{
t = new System.Timers.Timer(interval);
}
public void Start()
{
t.Start();
}
public void AddElapsedEventHandler(ElapsedEventHandler handler)
{
t.Elapsed += (sender, e) =>
{
try
{
handler(sender, e);
}
catch (Exception ex)
{
if (Error != null)
{
Error(ex);
}
else
{
throw;
}
}
};
}
}