如何在none控件类内调用某些方法 [英] How Invoke Some method inside of none Control Class

查看:69
本文介绍了如何在none控件类内调用某些方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一些委托和事件来实现NamedPipes,如下所示:

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);

}

当我在Form类(继承自Control对象)中使用此事件时,实现是:

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
  }
}

但是当我想在不继承自控制对象的其他一些类中使用此方法时,我既不能使用Invoke任何方法,也不能替换在上升的Invoker方法pipeServer_MessageReceived中目标方法Do_pipeServer_MessageReceived的实现.一个例外,那么您的建议是什么?

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?

推荐答案

有两种可能性:您需要在GUI线程上调用回调,否则就不需要.

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

如果您不触摸该回调中的GUI,则不必理会这些调用.

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

如果执行触摸GUI,那么根据定义,您必须具有对要更新的 some 控件的引用.在该控件上调用Invoke.调用Invoke的控件确实无关紧要;他们都会做同样的事情.

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.

这篇关于如何在none控件类内调用某些方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆