1

尝试设置一个订阅服务并在事件发生时通过回调通知我的服务器工具。我的订阅部分正在工作,当一个事件被触发时,它会触发回调,但我在一个库中有这个并且想把它放到主项目中。我想用委托来做,但想不出语法。

客户订阅者.cs

/// <summary>
/// Used by Clients to subscribe to a particular queue
/// <param name="type">Subscription type being subscribed to by client</param>
/// <returns></returns>
public bool Subscribe(string type,)
{
    bool IsSubscribed = false;
    try
    {
        switch (type)
        {
            case "Elements":
            {
                logger.Info("Subscribing toPublisher");
                Subscriber.SubscribeToElements(ElementResponse);
                logger.Info("Subscription Completed");
                IsSubscribed = true;
                break;
            }
        }
    }    
    catch (Exception ex)
    {
        logger.Error(ex);
    }

    return IsSubscribed;
}


public void ElementResponse(Element element, SubscriptionEvent.ActionType eventActionType)
{
    try
    {
        //  stuff to Do
        // Need to Callback to main application
    }
    catch (Exception ex)
    {
        logger.Error(ex);
        throw;
    }
}

程序.cs

static void Main(string[] args)
{
    SubscriberClient client = new SubscriberClient();
    client.Subscribe("SlateQueueElements");

    while (true)
    {
        ConsoleKeyInfo keyInfo = Console.ReadKey(true);

        if (keyInfo.Key == ConsoleKey.X)
            break;
    }
}

那么如何将元素响应信息返回到主项目呢?

4

1 回答 1

2

如果你想有一个回调,那么你需要指定一个作为参数。我做了一些假设,但这应该可行:

public bool Subscribe(string type, Action callback)
{
    bool IsSubscribed = false;
    try
    {
        switch (type)
        {
            case "Elements":
            {
                logger.Info("Subscribing toPublisher");
                Subscriber.SubscribeToElements((e,t) => ElementResponse(e,t,callback));
                logger.Info("Subscription Completed");
                IsSubscribed = true;
                break;
            }
        }
    }    
    catch (Exception ex)
    {
        logger.Error(ex);
    }

    return IsSubscribed;
}

public void ElementResponse(Element element, SubscriptionEvent.ActionType eventActionType, Action callback)
{
    try
    {
        //  stuff to Do
        callback();
    }
    catch (Exception ex)
    {
        logger.Error(ex);
        throw;
    }
}

我使用了一个Action委托,但只要你有办法调用它,任何东西都可以放在它的位置。程序代码将是:

static void Main(string[] args)
{
    SubscriberClient client = new SubscriberClient();
    client.Subscribe("SlateQueueElements", () => 
    {
       Console.WriteLine("Calling back...");
    });

    while (true)
    {
        ConsoleKeyInfo keyInfo = Console.ReadKey(true);

        if (keyInfo.Key == ConsoleKey.X)
            break;
    }
}
于 2012-09-05T23:39:15.160 回答