从表格处理类中的自定义事件

时间:2018-07-04 20:36:08

标签: c# winforms events websocket

我在尝试处理我创建的事件时遇到问题。我正在尝试使用WebSockets,当我收到一条消息时,我想引发一个事件,我的一个表单可以订阅该事件。

在我的Form_Load事件中。我有:

taskRoutingServer = new Core.WebSocketServerWrapper();
taskRoutingServer.MessageReceivedEvent += 
TaskRoutingServer_MessageReceivedEvent1;

我表单中的方法如下:

private void TaskRoutingServer_MessageReceivedEvent1(object sender, WebSocketSharp.MessageEventArgs e)
{
    throw new NotImplementedException();
}

我打算处理和使用'e',它将包含我的表单需要使用的数据。我拥有的WebSocket类如下:

public class WebSocketServerWrapper : WebSocketBehavior
{
  private WebSocketServer socketServer;
  public delegate void MessageReceivedEventHandler(object sender, MessageEventArgs e);
  public event MessageReceivedEventHandler MessageReceivedEvent;
  public string creator;

  public WebSocketServerWrapper()
  {
      socketServer = new WebSocketServer("ws://localhost:9001");
      socketServer.AddWebSocketService<WebSocketServerWrapper>("/ws");
  }

  public bool IsListening()
  {
      return socketServer.IsListening;
  }

  public void StartListening()
  {
      socketServer.Start();
  }

  public void StopListening()
  {
      socketServer.Stop();
  }

  protected override void OnMessage(MessageEventArgs e)
  {
      //invoke event
      MessageReceivedEvent?.Invoke(this, e);
  }
}

当前的行为是触发OnMessageMessageReceivedEvent为null,因此不调用该事件。我应该如何正确处理此事件?

1 个答案:

答案 0 :(得分:1)

MessageReceivedEvent此时不应为null:

MessageReceivedEvent?.Invoke(this, e);

添加了侦听器后,您在OnLoad中编写了该侦听器:

taskRoutingServer.MessageReceivedEvent += TaskRoutingServer_MessageReceivedEvent1;

这可能意味着您是

  1. 不在同一实例(onLoad中的taskRoutingMessage对象)上触发事件,或者
  2. 您已经删除了监听器。

如果框架以某种方式自动创建了“ WebSocketBehaviour”,它将不是同一实例。然后,您可以尝试使用静态事件处理程序:

    public static event MessageReceivedEventHandler MessageReceivedEvent;

    protected override void OnMessage(MessageEventArgs e)
    {
        MessageReceivedEvent?.Invoke(this, e);
    }

...并在加载中进行如下设置:

Core.WebSocketServerWrapper.MessageReceivedEvent += 
                              TaskRoutingServer_MessageReceivedEvent1;