How Invoke Some method inside of none Control Clas

2019-08-16 23:05发布

问题:

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.