2012-09-05 4 views
1

서비스에 가입하고 콜백을 통해 이벤트가 발생하면 알려주는 서버 도구를 설정하려고합니다. 구독 부분이 작동하고 이벤트가 트리거되면 콜백에 도달하지만 라이브러리에있는이 이벤트를 주 프로젝트에 가져 오려고합니다. 나는 델리게이트와 함께 생각했지만 구문을 생각할 수는 없었다.콜백 내 콜백 C#

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

그래서 다시 주요 프로젝트에 요소 응답 정보를 얻는 방법?

답변

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; 
    } 
} 
+0

감사합니다. 작동합니다. 구독이 밝혀 졌는데, 객체 형식의 매개 변수를 제공하여 전달할 수있었습니다. 나는 델리게이트를 사용하여 끝내지 만, 이것이 똑같이 작동하는 것을 볼 수 있습니다. 다시 한 번 감사드립니다! – gcoleman0828