开发者

Disposing IDisposable items generated by Observable

I have an Observable<WebResponse> (WebResponse implements IDisposable)

responseObservable
    .Where(webResponse => webResponse.ContentType.StartsWith("text/html"))
    .Select(webResponse => webResponse.ContentLength)
    .Run()

(Ignore the pointle开发者_StackOverflow中文版ssness of the query!)

so, I'm discarding WebResponse instances without calling Dispose on them. This seems bad.

More abstractly: If I have an Observable<IDisposable>, how do I deal with the disposal of generated items?


Assuming that you have a method WebResponse CreateMyWebResponse() use Observable.Using like this:

var responseObservable = Observable.Using(() => CreateMyWebResponse(), Observable.Return);


Change the Where and Do bits to something like

.Do(webResponse => {
    if (webResponse.ContentType.StartsWith("text/html")) 
        ProcessAndDispose(webResponse);
    else
        webResponse.Dispose(); })

perhaps?

EDIT

Based on your edit, how about

.Select(webResponse => {
    int r = -1;
    if (webResponse.ContentType.StartsWith("text/html")) 
        r = webResponse.ContentLength;
    webResponse.Dispose(); 
    return r; })
.Where(i => i != -1)

now? This would generalize into something like

FilterProjectDispose(e, pred, proj) {
    e.Select(x => {
        using(x) {
            if (pred(x)) return Some(proj(x));
            else return None; }})
     .Where(x => x.IsSome)
     .Select(x => x.Value)
}

assuming Some/None as in F# (I am apparently starting to forget my C#).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜