How Invoke Some method inside of none Control Class

不想你离开。 提交于 2019-12-11 14:43:54

问题


I use some Delegate and Events to Implement NamedPipes like this:

public delegate void MessageReceivedHandler(byte[] message, Client client);

public event MessageReceivedHandler MessageReceived;

void ListenForClients() {

//Do some

Thread readThread = new Thread(Read) { IsBackground = true };

}

void Read(object clientObj) {

//Do Some

if(MessageReceived != null)
MessageReceived(ms.ToArray(),client);

}

When I Use this event in Form Class(Inherited from Control object) the Implementation is:

public partial class Form1 : Form {

public Form1(){
    pipeServer.MessageReceived += pipeServer_MessageReceived;
}

  void pipeServer_MessageReceived(byte[] message, PipeServer.Client client) {

      Invoke(new PipeServer.MessageReceivedHandler(Do_pipeServer_MessageReceived),
                    new object[] { message, client });
  }

  public void Do_pipeServer_MessageReceived(byte[] message, PipeServer.Client client) {
  // Do Some
  }
}

But when I want use this in some other classes that not inherited from control object I can't Invoke any methods and also I can't Replace implementation of target method Do_pipeServer_MessageReceived in Invoker method pipeServer_MessageReceived that rise an exception, so what is your suggestion?


回答1:


There are two possibilities: you need to invoke the callback on the GUI thread, or you don't.

If you don't touch the GUI in that callback then don't bother with the invokes.

If you do touch the GUI, then you must by definition have a reference to some control you're updating. Call Invoke on that control. It really doesn't matter which control you call Invoke on; they'll all do the same thing.



来源:https://stackoverflow.com/questions/8787550/how-invoke-some-method-inside-of-none-control-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!