Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate - Exceptions don't wait until calling EndInvoke()

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 Exceptions (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!

like image 260
Luca Nate Mahler Avatar asked Oct 07 '22 23:10

Luca Nate Mahler


1 Answers

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":

enter image description here

Ignore that; the IDE doesn't always get it right. That is still handled.

like image 85
Marc Gravell Avatar answered Oct 13 '22 12:10

Marc Gravell