处理GCM库的不同事件?

时间:2013-12-31 07:34:53

标签: c# android

我在C#中使用GCMlibrary。我已经实现了不同的处理程序来检查是否发送了消息。如何检查

的处理程序
  1. ChannelException
  2. ChannelDestroyed
  3. ServiceException
  4. 我如何检查这些事件中何时出现异常。

    我已经声明了这样的处理程序

    static void ChannelException(object sender, IPushChannel channel, Exception exception)
        {
            CLogger.WriteLog(ELogLevel.INFO, "Channel Exception: " + sender + " -> " + exception);
            // Console.WriteLine("Channel Exception: " + sender + " -> " + exception);
        }
    
    static void ServiceException(object sender, Exception exception)
        {
            CLogger.WriteLog(ELogLevel.INFO, "Service Exception: " + sender + " -> " + exception);
            string test= exception.Message;
            // Console.WriteLine("Channel Exception: " + sender + " -> " + exception);
        }
    
    static void ChannelDestroyed(object sender)
        {
            CLogger.WriteLog(ELogLevel.INFO, "Channel Destroyed for: " + sender);
            // Console.WriteLine("Channel Destroyed for: " + sender);
    
        }
    

1 个答案:

答案 0 :(得分:0)

要在C#中处理事件中的异常,请使用MSDN中的示例。使用以下事件提出方法:

public class Pub
{
    public event EventHandler OnChange = delegate { };
    public void Raise()
    {
        var exceptions = new List<Exception>();
        foreach (Delegate handler in OnChange.GetInvocationList())
        {
            try
            {
                handler.DynamicInvoke(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        }
        if (exceptions.Any())
        {
            throw new AggregateException(exceptions);
        }
    }
}

如上所述捕捉异常:

public void CreateAndRaise()
{
    Pub p = new Pub();
    p.OnChange += (sender, e)
    => Console.WriteLine(“Subscriber 1 called”);
    p.OnChange += (sender, e)
    => { throw new Exception(); };
    p.OnChange += (sender, e)
    => Console.WriteLine(“Subscriber 3 called”);
    try
    {
        p.Raise();
    }
    catch (AggregateException ex)
    {
        Console.WriteLine(ex.InnerExceptions.Count);
    }
    // Displays
    // Subscriber 1 called
    // Subscriber 3 called
    // 1
}

如果您无法更改现有的事件处理程序,则:

  1. 编写您自己的事件处理程序,它包装现有的,例如ChannelEventCustom
  2. 在其raise方法中,在ChannelEvent块中包装现有的事件执行(例如try-catch
  3. 就是这样。这是short guide how to create your own events