等待WCF回调时如何保持控制台应用程序运行?

时间:2019-07-19 08:32:15

标签: c# .net wcf

我正在编写一个程序,该程序接收来自第三方服务的实现回调。我目前正在通过Console.ReadLine保持应用打开状态,但是不确定在等待用户输入时是否冻结了整个程序?否则我的回调不起作用。

请耐心等待,第一次使用.net;得到了大部分代码,特别是第三方api文档上的callbackevents。

主要:

public static void Main(string[] args)
{
   Console.WriteLine("Hello World!");
   var callback = new ThirdPartyCallbackImplementation();
   var context = new InstanceContext(callback);
   ThirdPartyClient client = new ThirdPartyClient(context);

   callback.FoundEvent += CallbackOnFoundEvent;
   client.Subscribe();

   Console.ReadLine();
}

private static void CallbackOnFoundEvent(object info) 
{
   Console.WriteLine("Something was found!");
}

ThirdPartyCallbackImplementation:

public delegate void CallBackEvent(object info);

[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple,
    UseSynchronizationContext = false, ValidateMustUnderstand = false)]

public class ThirdPartyCallbackImplementation : ThirdPartyCallback
{
   public event CallBackEvent FoundEvent;

   private void OnFound(object info)
   {
      this.FoundEvent?.Invoke(info);
   }

   // function implementation
   public void Found()
   {
      CallBackEvent c = this.OnFound;
      c.BeginInvoke(result, ar => { }, null);
   }
}

完全没有错误。它只是在说Hello World!。 API具有其自己的接口并且可以正确触发,因此肯定可以正常工作。

1 个答案:

答案 0 :(得分:0)

我首选的解决方案是利用Rx事件扩展

public async static Task Main(string[] args)
{
   var callback = new ThirdPartyCallbackImplementation();
   var context = new InstanceContext(callback);
   ThirdPartyClient client = new ThirdPartyClient(context);


   client.Subscribe();
   object info = await callback.WhenEventFound()
                      //timeout
                      .Take(TimeSpan.FromSeconds(10))
                      .FirstOrDefaultAsync()
                      .ToTask();
   if(info != null)
      Console.WriteLine("Something was found!");

   Console.ReadLine();
}

private static IObservable<object> WhenEventFound(this ThirdPartyCallbackImplementation proxy)
{
     return Observable.FromEvent<CallBackEvent, object>(h => x => h(x),
            handler => proxy.FoundEvent += handler,
            handler => proxy.FoundEvent -= handler)
}

这段代码看起来很像一个从Java移植的库,可能是Ignite.net。