public void OnReceive(IAsyncResult asyncResult) { try { if (udpClient.Client == null) { return; } lock (udpClient) { var endPoint = new IPEndPoint(IPAddress.Any, 0); var bytes = udpClient.EndReceive(asyncResult, ref endPoint); var message = Message.FromBytes(bytes); switch (message.Type) { case MessageType.ChatMessage: OnChatMessage(message as ChatMessage); break; case MessageType.Contacts: OnContactsMessage(message as ContactsMessage); break; case MessageType.LoginAccepted: OnLoginAcceptedMessage(message as LoginAcceptedMessage); break; case MessageType.LogoutAccepted: OnLogoutAcceptedMessage(message as LogoutAcceptedMessage); break; default: throw new ArgumentOutOfRangeException("Unknown message was received."); } udpClient.BeginReceive(this.OnReceive, null); } } catch (Exception ex) { clientView.ShowException(ex); } }