我使用FromEventPattern,我希望能夠做一些清理工作,我觀察到的finally塊。現在finally塊沒有被調用。這是我的理解,我不得不打電話給OnCompleted ...某處,但不知道如何實現。從我的Silverlight程序的某些代碼:爲什麼最後不會調用我的DownloadStringAsync Observable?
public IObservable<string> StartDownload (string uri)
{
WebClient wc = new WebClient();
var o = Observable.FromEventPattern<DownloadStringCompletedEventArgs>(wc, "DownloadStringCompleted")
.Select(s => s.EventArgs.Result);
wc.DownloadStringAsync(new Uri(uri));
return o;
}
public void TestRx()
{
var anobs = StartDownload("http://www.google.com");
anobs
.Subscribe(stuff =>
{
// do stuff
});
anobs
.Finally(() =>
{
// not called?
});
}
UPDATE: 顯然,我的假設是OnCompleted()將解決我的問題是錯誤的。我嘗試將StartDownload更改爲以下內容,最後仍未調用。這裏發生了什麼?
public IObservable<string> StartDownload (string uri)
{
WebClient wc = new WebClient();
var subject = new AsyncSubject<string>();
wc.DownloadStringCompleted += (sender, e) =>
{
if (e.Error != null)
subject.OnError(e.Error);
subject.OnNext(e.Result);
subject.OnCompleted();
};
wc.DownloadStringAsync(new Uri(uri));
return subject;
}
見我的回答類似的問題: http://stackoverflow.com/questions/3801505/使用rx-to-simplify-an-asynchronous-silverlight-web-service-request/3808990#3808990 – 2012-01-05 14:26:33