Reactive Extensions简介一
在.Net 4.0中引入了兩個新的接口用來實現觀察者模式——IObservable和IObserver。IObservable是數據源,IObserver是觀察者,觀察者訂閱數據源后,當新的數據產生時,將其主動傳給所有的訂閱者(Iobserver)。
觀察者模式比較基礎,因此在這里并不多加介紹,沒有相關基礎的朋友可以參看MSDN的這兩個鏈接。
l?Observer(觀察器)
l?探究觀察者設計模式
這里我用一個簡單的實例介紹一下這個接口的基本用法。
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? var timerServer = new TimeServer();
??????????? timerServer.Subscribe(new Watch());
?
??????????? System.Threading.Thread.Sleep(-1);
??????? }
??? }
?
??? class TimeServer : IObservable<DateTime>
??? {
??????? public TimeServer()
??????? {
??????????? new System.Threading.Timer(_ => Notify(DateTime.Now), null, 0, 1000);
??????? }
?
??????? void Notify(DateTime time)
??????? {
??????????? foreach (var observer in _observers)
??????????? {
??????????????? observer.OnNext(time);
??????????? }
??????? }
?
??????? #region IObservable<DateTime> 成員
?
??????? List<IObserver<DateTime>> _observers = new List<IObserver<DateTime>>();
?
??????? public IDisposable Subscribe(IObserver<DateTime> observer)
??????? {
??????????? //這里省略了參數有效性檢查
??????????? _observers.Add(observer);
??????????? return new AnonymousUnSubscriber() { Action = () => _observers.Remove(observer) };
??????? }
?
??????? #endregion
?
??????? #region AnonymousUnSubscriber類
?
??????? class AnonymousUnSubscriber : IDisposable
??????? {
??????????? public Action Action { get; set; }
?
??? ??????? void IDisposable.Dispose()
??????????? {
??????????????? this.Action();
??????????? }
??????? }
?
??????? #endregion
??? }
?
??? class Watch : IObserver<DateTime>
??? {
??????? #region IObserver<DateTime> 成員
?
??????? public void OnCompleted() { throw new NotImplementedException(); }
??????? public void OnError(Exception error) { throw new NotImplementedException(); }
?
??????? public void OnNext(DateTime value)
??????? {
??????????? Console.WriteLine(value);
??????? }
?
??????? #endregion
??? }
?
這里定義了兩個簡單的對象:TimeServer是數據源,實現了IObservable接口,Watch是觀察者,實現了IObserver接口。當有新數據產生時(定時器每秒鐘通知一次),會調用Watch的OnNext接口,將當前時間在屏幕上打印出來。
像這種“推”的方式一般也被稱作反應式(Reactive),雖然其接口比較簡明,但在.Net 4.0中只有接口的聲明,并沒有其它的相關庫函數進行支持。因此要實現反應式編程得自己實現所有其它的相關代碼。不過好在微推出了一個名為Reactive Extensions for .NET (Rx)的庫,實現了許多強有力的功能,使得我們能快速構建強大的反應式的程序。像上面的這個例子,用Rx庫可以簡化如下:?
??? static void Main(string[] args)
??? {
??????? var timerServer = Observable.Interval(TimeSpan.FromSeconds(1)).Select(_ => DateTime.Now);
??????? timerServer.Subscribe(i => Console.WriteLine(i));
?
??????? System.Threading.Thread.Sleep(-1);
??? }
?
Rx庫非常強大,由于相關資料不多,目前我也是在學習和摸索中,后面還會寫一些文章陸續介紹這個庫。
?
轉載于:https://www.cnblogs.com/TianFang/archive/2011/05/01/2034083.html
總結
以上是生活随笔為你收集整理的Reactive Extensions简介一的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: perl学习4--调用子程序
- 下一篇: 无线网络连接无法停用