
Scenario: I am building a client / socket class library to then use in other applications. This library will raise events such as Connected, SendComplete etc. The problem I am having is that my event is always null when using it in a AsyncCallback method - I believe this is to do with it being on a different thread it cannot be seen?
Listen Method
/// <summary> /// Starts the server listening for connections /// </summary> public void Listen() { _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, _localPort); _serverSocket.Bind(ipEndPoint); _serverSocket.Listen(_maxPendingConnections); // start accepting client connections _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); // change state to listening //_ncState = NetCommStates.Listening; }
AcceptCallback
/// <summary> /// Handles the connection request from the client establishing connection with the server (handshake / accepted) /// </summary> /// <param name="ar"></param> private void AcceptCallback(IAsyncResult ar) { // assign client socket meaning connection established with the server Socket acceptedClientSocket = _serverSocket.EndAccept(ar); // raise OnConnected event NetCommConnectedEventArgs e = new NetCommConnectedEventArgs(((IPEndPoint)acceptedClientSocket.RemoteEndPoint).Address.ToString(), ((IPEndPoint)acceptedClientSocket.RemoteEndPoint).Port); OnConnected(e); // begin listening for new connections _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); // add client AddClient(acceptedClientSocket); }
Events / Event Handler
/// <summary> /// Occurs when connection is achieved (client and server). /// </summary> public event EventHandler<NetCommConnectedEventArgs> Connected; /// <summary> /// Raises the Connected event. /// </summary> private void OnConnected(NetCommConnectedEventArgs e) { EventHandler<NetCommConnectedEventArgs> handler = Connected; // Connected is null - is this because of thread issues? (see attached image) if (handler != null) { handler(null, new NetCommConnectedEventArgs(e.SourceIP, e.SourcePort)); } }
Any idea of how to get my OnConnected event to see the event handler correctly?
Any thoughts / points appreciated
