如何将套接字监听为 IEnumerable?

在以下代码中,我可以订阅套接字并接收消息。在某个 IO 线程中接收到消息。


var subscription = SubscribeToStreamAsync( msg => { } ).Result;

...

Unsubscribe( subscription );

foreach我想在通常的循环中收听这些消息。所以,我需要在我的线程中路由消息并将流返回为IEnumerable.


foreach(var item in GetStreamAsync().Result) {

    if (item == ...) break;

}

我可以通过System.Collections.Concurrent吗?


而且我不想使用System.Reactive.


qq_遁去的一_1
浏览 87回答 1
1回答

慕侠2389804

我已经完成了以下方式。只是我担心如果套接字/服务器发生任何问题,线程会冻结。var collection = new BlockingCollection<object>();var subscription = SubscribeToStreamAsync().Result;try {&nbsp; &nbsp; var enumerable = collection.GetConsumingEnumerable();&nbsp; &nbsp; foreach (var item in enumerable) {&nbsp; &nbsp; &nbsp; &nbsp; yield return item;&nbsp; &nbsp; }} finally {&nbsp; &nbsp; // foreach or stream is completed&nbsp; &nbsp; Unsubscribe( subscription ).Wait();}
打开App,查看更多内容
随时随地看视频慕课网APP