FromAsyncPattern 会处置不再使用的资源吗?
FromAsyncPattern 会关闭我的网络响应吗:
var o = Observable.Return(HttpWebRequest.Create("http://foo.com"))
.SelectMany(r => Observable.FromAsyncPattern<WebResponse>(
r.BeginGetResponse,
r.EndGetResponse)())
.Select(r => r.ContentLength);
// The response is now disposed
还是我必须手动执行此操作?
var o = Observable.Return(HttpWebRequest.Create("http://foo.com"))
.SelectMany(r => Observable.FromAsyncPattern<WebResponse>(
r.BeginGetResponse,
r.EndGetResponse)())
.Select(r => Tuple.Create(r, r.ContentLength))
.Do(t => t.Item1.Close())
.Select(t => t.Item2);
如果我必须手动完成,还有比这更好的方法吗?
Will FromAsyncPattern close my webresponse:
var o = Observable.Return(HttpWebRequest.Create("http://foo.com"))
.SelectMany(r => Observable.FromAsyncPattern<WebResponse>(
r.BeginGetResponse,
r.EndGetResponse)())
.Select(r => r.ContentLength);
// The response is now disposed
Or do I have to do it manually?
var o = Observable.Return(HttpWebRequest.Create("http://foo.com"))
.SelectMany(r => Observable.FromAsyncPattern<WebResponse>(
r.BeginGetResponse,
r.EndGetResponse)())
.Select(r => Tuple.Create(r, r.ContentLength))
.Do(t => t.Item1.Close())
.Select(t => t.Item2);
If I have to do it manually, is there a better way than this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Observable.Using
可用于此目的,如下所示:Observable.Using
can be used for this purpose as:作为
Using
查询的稍微简洁的版本是这样的:我建议将
Scheduler.ThreadPool
添加到至少第一个Return
以使可观察在后台线程上执行 - 否则默认为Scheduler.Immediate
。As slightly cleaner version of the
Using
query would be this:I would suggest adding
Scheduler.ThreadPool
to at least the firstReturn
to make the observable execute on a background thread - the default isScheduler.Immediate
otherwise.我不相信
FromAsyncPattern
可以关闭您的资源,即使它想这样做。它没有足够的信息来了解如何在其他地方使用进行异步调用的对象(本例中为 HttpWebRequest)或从异步调用返回的对象(本例中为 WebResponse)来了解何时将其保存到处置
。也就是说,您仍然可以手动关闭资源,而无需额外的
Do
和Select
调用。只需将第一个示例中的Select
更改为:据我所知,唯一会调用
Dispose
的 Rx 运算符是Observable.Using
。然而,根据它的签名,它如何或是否可以应用在这里并不是很明显,所以我采用了上述方法。I do not believe that
FromAsyncPattern
could close your resources, even if it wanted to. It does not have enough information about how either the object on which it is making the async calls (HttpWebRequest in this case) or the object returned from the async calls (WebResponse in this case) will be used elsewhere to know when it is save toDispose
.That said, you can still close the resources manually without the extra
Do
andSelect
calls. Just change theSelect
in the first example to:The only Rx operator that will call
Dispose
that I know of isObservable.Using
. However, based on its signature, it was not immediately obvious how or if it could apply here, so I went with the above approach.