locked
Attempt to unsubscribe the DatagramSocket (C++) from MessageReceived results in Exception

    Question

  • Hi

    I'm trying to unsubscribe the DatagramSocket  (C++) from MessageReceived and getting the exception: A method was called at an unexpected time.

    This is the code to create/bind the socket:

    mySocket = ref new DatagramSocket();
    listenerContext = ref new ListenerContext(this, mySocket);
    
    //myRegToken is EventRegistrationToken 
    isListening = true;
    myRegToken = mySocket->MessageReceived += ref new TypedEventHandler<DatagramSocket^, DatagramSocketMessageReceivedEventArgs^>(listenerContext, &ListenerContext::OnMessage);
    

    Then at some point later I do:

    if (isListening)
    {
    	mySocket->MessageReceived -= myRegToken;
    }
    

    And I get an exception.

    I was trying with different locations for the unsubscribe (UI Thread - button click handler, the message read event) but the result is the same.

    What am I doing wrong?

    Thanks,

    Rafi

    Tuesday, April 23, 2013 7:33 AM

Answers

All replies