C#中的动作委托

我正在审查 API 示例应用程序中的一些代码,需要一些帮助来更好地理解Action<T>整个示例应用程序中的委托。我在整个代码中提出了几个问题。任何帮助表示赞赏


API 在Client.cs类中实现,当我从应用程序发出请求时,API 会将响应发送到Client.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 交互并将信息反馈回 UI,以便用户可以查看返回的数据


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


沧海一幻觉
浏览 182回答 1
1回答

波斯汪

从文档事件是一种特殊的多播委托,只能从声明它们的类或结构(发布者类)中调用。如果其他类或结构订阅了该事件,则在发布者类引发事件时将调用它们的事件处理程序方法因此,Client.cs您有一个名为TickSize.&nbsp;此委托使其他类能够订阅与其关联的事件。所以在你的函数中void tickSize(int tickerId, int field, int size),你想让所有其他订阅者知道一个滴答事件发生了。为此,您首先要查看是否有任何订阅者。这是null检查发生的地方if (tmp != null)。已经tmp没有必要,你可以做if(TickSize != null)。如果您有任何注册的事件处理,它会火和订户将收到的呼叫。在您的情况下,您确实有订阅者,因为您public AppDialog使用以下代码订阅事件:client.TickSize += client_TickSize;所以无论何时void tickSize(...)被调用 in&nbsp;Client.cs,代码void client_TickSize(...)都会运行。这将调用HandleMessagewhich 将检查它是否需要由Invoke函数调用,因为调用代码不在 UI 线程上。如果确实需要使用Invoke调用它,它将使用当前控件的Invoke函数调用相同的消息(不确定哪个控件,可能是Form)。然后HandleMessage将看到Invoke不需要,因为调用者在 UI 线程上,然后它将调用UpdateUi将更新控件。
打开App,查看更多内容
随时随地看视频慕课网APP