Wednesday, August 25, 2010

Rx sample

In this post i have implemented a simple program which writes all the information of a customer class to a file.I took this example as it can be functional in a very short period of time.The code in this blog is inspired from Rx wiki.


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Concurrency;
using System.Diagnostics;

namespace ObservablePrototype
{
public class Prototype
{
string errorfile = ConfigurationManager.AppSettings["CustomerFile"];

public void RunProto()
{
Stopwatch sw = new Stopwatch();
sw.Start();

//Making Customer as observableCollection 
var customers = new ObservableCollection();

// adding event handler 
var customerChanges = Observable.FromEvent(
(EventHandler ev)
=> new NotifyCollectionChangedEventHandler(ev),
ev => customers.CollectionChanged += ev,
ev => customers.CollectionChanged -= ev);

//ling query for notify collection changed

var line = (from c in customerChanges
where c.EventArgs.Action == NotifyCollectionChangedAction.Add
from cu in c.EventArgs.NewItems.Cast().ToObservable()
select cu).BufferWithCount(10);

//using scheduler or u can just subscribe directly
Scheduler.ThreadPool.Schedule(() =>
{
line.Subscribe(cus =>
{
WriteCustomers(cus.ToList());
}
);
});

//start adding customers  
AddCustomers(customers);
WriteTimings(sw.Elapsed.Seconds + "Observable");
}

private void WriteTimings(string p)
{
TextWriter writer = new StreamWriter(errorfile, true);
writer.WriteLine(p);
writer.Close();
}



private void AddCustomers(ObservableCollection customers)
{
for (int i = 0; i < 50; i++)
            {
                Thread.Sleep(500);
                customers.Add(new Customer() { firstName = "K", lastName = "P" + i });
            }
            
        }



        public void StraightWrite()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            List customers = new List();
for (int i = 0; i < 50; i++)
            {
                Thread.Sleep(500);
                customers.Add(new Customer() { firstName = "K", lastName = "P" + i });
            }
            WriteCustomers(customers);
            WriteTimings(sw.Elapsed.Seconds + "Normal");
        }



        private void WriteCustomers(List customers)
{
foreach (var c in customers)
{
TextWriter writer = new StreamWriter(errorfile, true);
writer.WriteLine("FirstName : " + c.firstName + "  LastName : " + c.lastName);
writer.Close();
}
}

}
}