【问题标题】:How to check if an event has fired?如何检查事件是否已触发?
【发布时间】:2013-07-31 05:26:58
【问题描述】:

我的代码实现有问题。我目前正在使用 PushSharp 库,我想做的一件事是如果事件触发,我想根据它是什么事件返回一个真值或假值。代码如下:

public static bool SenddNotification()
{
var push = new PushBroker();

        //Wire up the events for all the services that the broker registers
        push.OnNotificationSent += NotificationSent;
        push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;

}


static bool DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
    {
        //Currently this event will only ever happen for Android GCM
        Console.WriteLine("Device Registration Changed:  Old-> " + oldSubscriptionId + "  New-> " + newSubscriptionId + " -> " + notification);
        return false;
    }

    static bool NotificationSent(object sender, INotification notification)
    {
        Console.WriteLine("Sent: " + sender + " -> " + notification);
        return true;
    }

所以我想要的是如果事件触发,根据发生的情况返回真或假,然后最终在第一个方法中返回这个值

【问题讨论】:

  • 那么,这是两种情况之一,还是两种情况都会发生?
  • 不应该出现同时触发的情况。
  • 我会说创建一个全局布尔值,并在您的事件中返回它,然后在您的第一个方法中返回它。但是,它并不漂亮。
  • 老实说,我不知道这意味着什么,我也不知道如何解决这个问题:P 所以......即使它不漂亮!任何帮助都会很好

标签: c# events pushsharp


【解决方案1】:

您可以设置一个全局布尔变量,并让您的事件设置该变量,然后让您的第一个方法返回它。像这样的:

private bool globalBool;

public static bool SenddNotification()
{
var push = new PushBroker();

        //Wire up the events for all the services that the broker registers
        push.OnNotificationSent += NotificationSent;
        push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;

        return globalBool;  
}


static bool DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
    {
        //Currently this event will only ever happen for Android GCM
        Console.WriteLine("Device Registration Changed:  Old-> " + oldSubscriptionId + "  New-> " + newSubscriptionId + " -> " + notification);
        globalBool = false;
    }

    static bool NotificationSent(object sender, INotification notification)
    {
        Console.WriteLine("Sent: " + sender + " -> " + notification);
        globalBool = true;
    }

当然,您必须在退回之前检查它是否有null,并妥善处理。

【讨论】:

  • 为什么我必须检查空值?
  • 哦,nvm...如果没有事件触发
  • @user2094139:没错。如果没有事件触发,那么它将返回 null,这可能会产生不希望的结果。
  • 所以我遇到了一些问题 1) 该名称在上下文中不存在 2) 它说我的返回类型错误..
  • @user2094139:什么名字?
猜你喜欢
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多