回调C#内的回调

时间:2012-09-05 22:56:57

标签: c# .net delegates callback

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

ClientSubscriber.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;
    }
}

Program.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;
    }
}

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

1 个答案:

答案 0 :(得分: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;
    }
}