I have this code:
using System;
using System.Runtime.Remoting.Messaging;
class Program {
static void Main(string[] args) {
new Program().Run();
Console.ReadLine();
}
void Run() {
Action example = new Action(threaded);
IAsyncResult ia = example.BeginInvoke(new AsyncCallback(completed), null);
// Option #1:
/*
ia.AsyncWaitHandle.WaitOne();
try {
example.EndInvoke(ia);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
*/
}
void threaded() {
throw new ApplicationException("Kaboom");
}
void completed(IAsyncResult ar) {
// Option #2:
Action example = (ar as AsyncResult).AsyncDelegate as Action;
try {
example.EndInvoke(ar);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
In many articles stands that when I call BeginInvoke
, all Exception
s (here from method threaded
) wait until I call EndInvoke
and will be thrown there. But it doesn't work, the Exception
("Kaboom") is "unhandled" and the program crashes.
Can you help me?
Thanks!
That works fine. When you say "and the program crashes", I'm wondering if you just have the IDE set to break on all exceptions. I get no crash with that - it writes "Kaboom" to the console, as we would expect. Try running it outside of the IDE or pressing ctrl+f5 instead of just f5.
I think you are just seeing the IDE being "helpful":
Ignore that; the IDE doesn't always get it right. That is still handled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With