2

I receive some controller from 3rd party API, then i register some event that controller exposes, the event callback handler is with signature:

public delegate void SomeCallbackFromAPI(Guid threadId, int someInt)

This is not good enough for me, I would like to receive the sender as well because i need to identify this controller from a list of controllers i hold, and the callback does not provide any other valid ID that i can recognize the controller with.

I DO know when this invokes, and if I can the sender I can cast it to my controller type.

Is there a way to get the sender of callback ?

Thanks

ilansch
  • 4,784
  • 7
  • 47
  • 96

3 Answers3

0

This is not possible. When a delegate is invoked it is just as a regular method call, so unless the caller is being passed as a parameter, as in EventHandler<T>, you can't grab it.

argaz
  • 1,458
  • 10
  • 15
0

Delegates contain Method and Target. You can make the delegate's target contain the info you need, provided you know the controller you're subscribing to when you register your delegate.

namespace So17022438CallbackHandlers
{
    delegate void ApiCallback (Guid threadId, int param);

    class Program {
        class Handler {
            public string Name;
            public ApiCallback Callback;

            public Handler (string name)
            {
                Name = name;
                Callback = (id, param) => OnApiCallback(Name, param);
            }
        }

        static void Main (string[] args) {
            var apis = new[] { new Api(), new Api() };
            apis[0].RegisterCallback(new Handler("Name1").Callback);
            apis[1].RegisterCallback(new Handler("Name2").Callback);
            apis[0].CallCallback();
            apis[1].CallCallback();
            Console.ReadKey();
        }

        static void OnApiCallback (string name, int param) {
            Console.WriteLine(name + " - " + param);
        }
    }

    class Api {
        private ApiCallback _callback;

        public void RegisterCallback (ApiCallback callback) {
            _callback = callback;
        }

        public void CallCallback () {
            _callback(new Guid(), 1);
        }
    }
}

Edit: Actually, no need for classes, it can be done solely with closures. :)

Athari
  • 33,702
  • 16
  • 105
  • 146
0

You can try to get the caller via the StackTrace class.

See this answer.

Community
  • 1
  • 1
Maarten
  • 22,527
  • 3
  • 47
  • 68