在以下代碼中,我可以訂閱套接字并接收消息。在某個 IO 線程中接收到消息。var subscription = SubscribeToStreamAsync( msg => { } ).Result;...Unsubscribe( subscription );foreach我想在通常的循環中收聽這些消息。所以,我需要在我的線程中路由消息并將流返回為IEnumerable.foreach(var item in GetStreamAsync().Result) { if (item == ...) break;}我可以通過System.Collections.Concurrent嗎?而且我不想使用System.Reactive.
1 回答

慕俠2389804
TA貢獻1719條經驗 獲得超6個贊
我已經完成了以下方式。
只是我擔心如果套接字/服務器發生任何問題,線程會凍結。
var collection = new BlockingCollection<object>();
var subscription = SubscribeToStreamAsync().Result;
try {
var enumerable = collection.GetConsumingEnumerable();
foreach (var item in enumerable) {
yield return item;
}
} finally {
// foreach or stream is completed
Unsubscribe( subscription ).Wait();
}
- 1 回答
- 0 關注
- 110 瀏覽
添加回答
舉報
0/150
提交
取消