代码之家  ›  专栏  ›  技术社区  ›  Adjit

C中的行动授权#

  •  0
  • Adjit  · 技术社区  · 7 年前

    我正在为一个API审查一个示例应用程序中的一些代码,需要一些帮助来更好地理解 Action<T> 整个示例应用程序的委派我在代码中提出了几个问题如有任何帮助,我们将不胜感激

    API在 Client.cs 类,当我从应用程序发出请求时,API将响应发送到 客户机.cs 已经实施。

    /*****  Client.cs  *****/
    
    public event Action<int, int, int> TickSize;
    
    void tickSize(int tickerId, int field, int size)
    {
        var tmp = TickSize;
    
        //What is the point of tmp, and why do we check if it is not null?
    
        if (tmp != null)
            //This invokes the Action? ie - fires the TickSize Action event?
            tmp(tickerId, field, size);
    }
    

    然后 UI.cs 类处理用户界面交互并将信息反馈回用户界面,以便用户可以看到返回的数据

    /*****  UI.cs  *****/
    
    //Delegate to handle reading messages
    delegate void MessageHandlerDelegate(Message message);
    
    protected Client client;
    
    public appDialog(){
        InitializeComponent();
        client = new Client();
        .
        .
        //Subscribes the client_TickSize method to the client.TickSize action?
        client.TickSize += client_TickSize;
    }
    
    void client_TickSize(int tickerId, int field, int size){
        HandleMessage(new Message(ticketID, field, size));
    }
    
    public void HandleMessage(Message message){
        //So, this.InvokeRequired checks if there is another thread accessing the method?
        //Unclear as to what this does and its purpose
        //What is the purpose of the MessageHandlerDelegate callback
        // - some clarification on what is going on here would be helpful
        if (this.InvokeRequired)
            {
                MessageHandlerDelegate callback = new MessageHandlerDelegate(HandleMessage);
                this.Invoke(callback, new object[] { message });
            }
            else
            {
                UpdateUI(message);
            }
    
    }
    
    private void UpdateUI(Message message) { handle messages }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   JohanP    7 年前

    the docs

    事件是一种特殊的多播委托,只能从声明它们的类或结构(发布者类)中调用如果其他类或结构订阅事件,则当发布者类引发事件时,将调用它们的事件处理程序方法

    所以在 Client.cs 您有一个名为 TickSize . 此委托使其他类能够订阅与其关联的事件所以在你的职责范围内 void tickSize(int tickerId, int field, int size) ,您希望让所有其他订户知道发生了tick事件。

    要做到这一点,首先要看看是否有订户在这里 null 签入发生在 if (tmp != null) . 有 tmp 不需要,你可以 if(TickSize != null) 如果您注册了任何eventhandler,它将启动,订阅者将收到该调用在您的情况下,您确实有订阅者,因为您正在订阅中的事件 public AppDialog 使用此代码: client.TickSize += client_TickSize;

    所以无论何时 void tickSize(...) 被召入 客户群 ,中的代码 void client_TickSize(...) 会跑的这将调用 HandleMessage 它将检查是否需要由 Invoke 函数,因为调用代码不在UI线程上如果需要调用它,请使用 援引 ,然后它将使用当前控件的 援引 函数(不确定哪个控件 Form ). 这个 手语 会看到的 援引 不是必需的,因为调用方位于UI线程上,然后它将调用 UpdateUi 它将更新控件。