c# - 如何在等待 WCF 回调时保持控制台应用程序运行?
问题描述
我正在编写一个从 3rd 方服务接收实现回调的程序。我目前正在通过 保持应用程序打开Console.ReadLine
,但是,我不确定它是否在等待用户输入时冻结了整个程序?或者我的回调不起作用。
第一次使用.net,请多多包涵;获得了大部分代码,特别是第三方 api 文档中的回调事件。
主要的:
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!");
}
第三方回调实现:
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 确实可以正常工作,因为它有自己的接口并且可以正确触发。
解决方案
我首选的解决方案是利用 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。
推荐阅读
- c - 是否有正则表达式来修剪两位小数后的数字?
- html - 没有Javascript的分页
- c++ - 从另一个 (arduino) 访问一个 cpp 文件中的变量
- google-cloud-platform - 处理 10req/s 并保存到云存储 - 推荐的方法?
- javascript - 为什么按钮不使用此代码更改颜色?
- java - 在 mockito 中使用 when().thenreturn() 时出现空指针异常
- node.js - 在 Cloud Functions 中,将 JSON 写入 Cloud Firestore 中的 Map 数据类型的语法是什么?
- r - 如果矩阵中不存在该变量,则跳过该变量
- rust - 接受`impl Borrow的论点是惯用的生锈吗
` 抽象 T 的引用和值? - html - 边界一直向右