【问题标题】:attaching handler that returns a value to an event c#附加将值返回给事件的处理程序c#
【发布时间】:2017-01-26 15:31:58
【问题描述】:

我有以下几点:

    public String AttachService(string whereClauseParam)
    {
        //Get Client object here
        Client c = new Client();
        string cookieFromRequest =   WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Cookie];
        tokenInfo.TryGetValue(cookieFromRequest, out c);
        string[] arr = new string[] { };
        c.AttachedServiceStatus += OnAttachedServiceStatus;
        string whereClause = whereClauseParam.ToString();
        //c.AttachService("binding.interface='query_em'", 8799989);

        return string.Format("attached");
    }

//处理程序代码如下:

    public string OnAttachedServiceStatus(Client sender, ClientServiceAttachedStatus status)
    {
        if (status.AttachStatus == AttachedStatus.Connected && status.ServiceAttachStatus == ServiceAttachStatus.Attached)
        { 
            //update the Client object in Dictionary
            Client c = new Client();

            var ou = tokenInfo.First(x => x.Value == sender);
            tokenInfo.TryGetValue(ou.Key.ToString(), out c);
            tokenInfo.TryRemove(ou.Key.ToString(), out c);
            tokenInfo.TryAdd(ou.Key.ToString(), sender);

            string[] statusInfoT = new string[200];
            statusInfoT[0] = status.ServiceId.ToString();
            statusInfoT[1] = status.AttachStatus.ToString();
            statusInfoT[2] = status.ServiceAttachStatus.ToString();
            statusInfoT[3] = status.VirtualServiceId.ToString();
            statusInfoT[4] = status.AttachToken.ToString();
            statusInfo.TryAdd(ou.Key.ToString(), statusInfoT);

            //update the UI with a Dispatch - TO BE DONE

        }

        return "Connected";
    }

上述 AttachService 方法有一个附加到事件“AttachedServiceStatus”的处理程序“OnAttachedServiceStatus”。 只要 OnAttachedServiceStatus 返回 void,一切正常。但是,我现在需要让处理程序 OnAttachedServiceStatus 返回一个字符串,但我无法正确附加处理程序。

我正在考虑使用 Func 委托,但不知道如何使用它。 请帮忙!

【问题讨论】:

  • 返回到哪里,究竟是什么?事件处理程序无效是有原因的,原因是您的代码没有调用它们,因此没有代码可以返回值。
  • 我希望处理程序“OnAttachedServiceStatus”将字符串返回给调用者“AttachService”,但我无法得到以下正确
  • c.AttachedServiceStatus += OnAttachedServiceStatus;

标签: c# events delegates


【解决方案1】:

首先,事件处理程序的签名由事件的委托类型定义。如果该委托返回void,则您不能附加任何其他方法。方法的参数和返回值都应该匹配 even 委托的签名。我相信AttachedServiceStatus 使用返回void 的委托。类似的东西:

public delegate void Action<T1, T2>(T1 arg1, T2 arg2)

事件是

public event Action<Client, ClientServiceAttachedStatus> AttachedServiceStatus

但是,如果您使用返回值的委托呢?例如

public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2)

您可以将事件声明为

public event Func<Client, ClientServiceAttachedStatus> AttachedServiceStatus

但这没有任何意义。因为 event 是一个委托。当您附加处理程序时,您实际上是在组合委托,创建类似委托列表(调用列表)的东西。此列表包含所有附加的处理程序。当你引发事件时,调用列表中的所有处理程序都会被一一调用,并且只返回最后一次调用的处理程序的结果。调用顺序未确定。所以你甚至不知道哪个处理程序返回了值。

(*) 虽然如果您手动调用每个处理程序而不是引发事件,仍然可以获得所有结果。请参阅下面的服务评论


更新

我希望处理程序“OnAttachedServiceStatus”返回一个字符串 来电者“AttachService”,但我无法得到以下正确

当您将处理程序附加到事件时,处理程序不会执行。它只是添加到事件的调用列表中。当Client 将引发 事件时,将执行事件处理程序。所以AttachService 不是这里的来电者。 Client 是来电者。而且您不能将字符串返回给AttachService。将处理程序附加到事件后,代码将退出AttachService 方法。稍后会引发事件,并执行处理程序,但不会与AttachService 方法相关。

【讨论】:

  • 虽然 default 行为确实会给你一个随机值,但你不能使用默认的添加/删除处理程序,或者不能简单地调用 Invoke 来调用处理程序,而是将它们分开并单独调用它们。这是非常不典型的,不太可能适用于大多数情况,但也不是不可能。话虽如此,OP似乎首先不拥有定义事件的类,他试图为附加处理程序的代码提供一个值,而不是调用事件的代码,所以这些都与他无关.
  • @Servy 关于手动委托调用的好点。但是,他试图为附加处理程序的代码提供值是什么意思?据我了解,他试图附加签名错误的处理程序,正如我上面所说的,这是不可能的
  • 谢尔盖感谢您的评论。实际上,AttachedServiceStatus 事件设置在我无权访问的 Wrapper 类中,因此无法修改委托。
  • 我对 Sergey 的回答投了票,因为它有助于我理解事件和代表。虽然它没有为我的问题提供解决方案
【解决方案2】:

我不确定您是否了解事件的工作原理。

    Client c = new Client();
    // ...
    c.AttachedServiceStatus += OnAttachedServiceStatus;

此处未调用 OnAttachedServiceStatus。相反,这告诉 Client 对象在引发 AttachedServiceStatus 事件时调用 OnAttachedServiceStatus 方法,这可能在将来的任何时候发生。这就像你告诉赛车手“当我说‘去’时,尽可能快地跑到终点线,然后告诉我你花了多少步才能到达终点”。赛车手不会立即开始跑步,也不会告诉你跑了多少步;他们准备好等待。当您说“开始”时,他们就会执行您的指令并开始运行。当你得到他们的回应时,已经是在你指示他等待之后了。

从外观上看,您正在尝试建立远程连接,并希望从服务器确认连接确实已建立。如果使用事件来传达该信息,您将需要使用 EventArgs 来携带它。您应该能够通过以下方式实现这一目标:

客户端:

public String ConnectToServer(string whereClauseParam)
{
    //Create Server object here
    Server s = new Server();
    s.AttachedServiceStatus += OnAttachedServiceStatus;
    s.AttachService(this, whereClauseParam, 8799989);
}


public void OnAttachedServiceStatus (object sender, ClientServiceAttachedEventArgs e)
{
    if (e.AttachStatus == AttachedStatus.Connected && e.ServiceAttachStatus == ServiceAttachStatus.Attached)
    { 
        // Update the UI with the message from the server.
        MessageBox.Show(e.Message);

        // If you need to do something else with the server in response, you can do this:
        ((Server)sender).Foo("bar");
    }
}

在服务器端,为您的事件定义自定义 EventArgs 类:

// By making this inherit from EventArgs, we can use the built-in EventHandler<T> delegate for the event itself.
public class ClientServiceAttachedEventArgs : EventArgs
{
    public AttachedStatus AttachStatus { get; set; }
    public ServiceAttachStatus ServiceAttachStatus  { get; set; }
    public string Message { get; set; }
    // You can put in as many properties as you want to carry the information back from the server.
}

并将其放入您的 Server 类中:

public event EventHandler<ClientServiceAttachedEventArgs> AttachedServiceStatus;

public String AttachService(Client client, string whereClauseParam, int code)
{
    // Do what you need to do to register the client.
    //...

    // Assuming everything went as planned, fire the event.
    // First, construct the EventArgs with information about the results of the connection.
    ClientServiceAttachedEventArgs e = new ClientServiceAttachedEventArgs();
    e.AttachStatus = AttachedStatus.Connected;
    e.ServiceAttachStatus = ServiceAttachStatus.Attached;
    e.Message = "Attached";

    // This is where your OnAttachedServiceStatus method in the client finally gets called. If the event handler were returning a string, this is where it would be returned to and I can't imagine this does you any good. 
    AttachedServiceStatus(this, e); 
}

这是一个相当基本的实现,您的情况可能更复杂,但它应该为您指明正确的方向。需要注意的重要一点是,您希望返回给客户端的字符串是作为 ClientServiceAttachedEventArgs 的一部分的事件,以及您的状态枚举。这是通过事件发送信息的首选方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多