C# Delegates

Delegates offer a great deal of power to the C# and they fundamentally alter the way C# works compared to Java. I came across an article about delegates in C# from one of the MSDN blogs.

Here is the link

The link has the code where you can simply understand just by reading scanning the code.

The funny part is the author has mentioned that if you still want to execute a delegate in a asynchronous way and still need more control on that, then try executing the delegate from a thread. It’s true. But I can’t imagine a situation why we call delegate as a new thread, rather we can simply use the new thread for the work.

But if you think a little more you can really understand that, author has a good point in that, which really explains and clears the confusion most of the people have on delegates, which is whether the delegates are synchronous or asynchronous.

Delegates can be called either synchronously or asynchronously.

Rajini Style App

 

Hi, I never thought of writing a post today. But this website made me to do so. http://www.desimartini.com/​allaboutrajni.htm

A tribute for the creativity of those guys, it’s simply cool. So what is it to have a Silverlight version of the Rajini style app.

No big worries here’s the code. I named it as Rajini Style app. The code is not a matter here, but I salute the creativity of those guys who really made us think.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.NetworkInformation;

namespace RajiniStyleApp
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
        }

        void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                textBlock1.Text = "You need to switch off the Internet \n in order to view the content";
            }
            else
            {
                textBlock1.Text = "Disconnected ... Runs on Rajini power >> \n visit :: http://www.desimartini.com/​allaboutrajni.htm ";
            }
        }
    }

 

You have to add the System.Net.NetworkInformation namespace.

Dinning Philosopher – C#

 

This post demonstrates another threading problem. There are many solutions for dinning philosopher problem. The famous one is to introduce a waiter for the table. Where the waiter acts as the monitor and the philosophers have to ask the waiter to take a fork. Another solution is that let the philosophers talk with themselves.

But this solution has a another simple mechanism, which avoids the dead lock by it’s own by randomizing the time a philosopher can hold a single fork. Having both the forks is not randomized, since having the both forks is a ready state for eating. So even the dead lock is about to occur it never lasts. And another threshold value is used as starvation count, which represents the maximum number of continuous thinking a philosopher can bare without considered being starved.

When running this algorithm you can notice that the philosophers may get starved (mainly if the starvation count is low) but it is almost impossible for a philosopher to starve forever.

Pure object orientation and C# techniques are used in developing this code. It is true that this code is not the best one when it comes to efficiency. This code can be improved in other ways. But still it provides a self time slicing feature for the dinning philosophers problem.

using System;
using System.Threading;

namespace DinningPhilosophers
{
    class Program
    {   
        static void Main(string[] args)
        { 
            Philosopher aristotle = new Philosopher(Table.Plastic,Table.Platinum,"Aristotle",4); 
            Philosopher palto = new Philosopher(Table.Platinum, Table.Gold,"Plato",5);
            Philosopher john = new Philosopher(Table.Gold, Table.Silver,"John Dewey",6);
            Philosopher augustine = new Philosopher(Table.Silver, Table.Wood, "Augustine",4);
            Philosopher thomas = new Philosopher(Table.Wood, Table.Plastic,"Thomas Aquinas",7);

            new Thread(aristotle.Think).Start();
            new Thread(palto.Think).Start();
            new Thread(john.Think).Start();
            new Thread(augustine.Think).Start();
            new Thread(thomas.Think).Start();

            Console.ReadKey();
        }

    }



    enum PhilosopherState { Eating, Thinking }


    class Philosopher
    {
        public string Name { get; set; }

        public PhilosopherState State { get; set; }

        // determines number of continuose thinkings, without being considered starving
        readonly int StarvationThreshold;

        // defines the right and the left side fork of a philosopher
        public readonly Fork RightFork;
        public readonly Fork LeftFork;

        Random rand = new Random();

        int contThinkCount = 0;

        public Philosopher(Fork rightFork, Fork leftFork, string name, int starvThreshold)
        {
            RightFork = rightFork;
            LeftFork = leftFork;
            Name = name;
            State = PhilosopherState.Thinking;
            StarvationThreshold = starvThreshold;
        }

        public void Eat()
        {
            // take the fork in the right hand
            if (TakeForkInRightHand())
            {
                // if got the fork in the right hand immediatley try to take the fork in the left hand
                if (TakeForkInLeftHand())
                {
                    // if got both forks then eat
                    this.State = PhilosopherState.Eating;
                    Console.WriteLine("(:::) {0} is eating..with {1} and {2}", Name, RightFork.ForkID, LeftFork.ForkID);
                    Thread.Sleep(rand.Next(5000, 10000));

                    contThinkCount = 0;

                    // place the forks back
                    RightFork.Put();
                    LeftFork.Put();
                }
                // got the right fork but not the left one
                else
                {
                    // wait for a small random period and try agian to get left fork
                    Thread.Sleep(rand.Next(100, 400));
                    if (TakeForkInLeftHand())
                    {
                        // if got the left fork then eat
                        this.State = PhilosopherState.Eating;
                        Console.WriteLine("(:::) {0} is eating..with {1} and {2}", Name, RightFork.ForkID, LeftFork.ForkID);
                        Thread.Sleep(rand.Next(5000, 10000));

                        contThinkCount = 0;

                        RightFork.Put();
                        LeftFork.Put();
                    }
                    // if couldn't get the fork even after the wait, out the right fork on the table
                    else
                    {
                        RightFork.Put();
                    }
                }
            }
            // if couldn't get fork on the right hand
            else
            {
                // get a fork the left hand
                if (TakeForkInLeftHand())
                {
                    // wait for a small random time period and then try acquire the right one
                    Thread.Sleep(rand.Next(100, 400));
                    if (TakeForkInRightHand())
                    {
                        // if got the right one then eat
                        this.State = PhilosopherState.Eating;
                        Console.WriteLine("(:::) {0} is eating..with {1} and {2}", Name, RightFork.ForkID, LeftFork.ForkID);
                        Thread.Sleep(rand.Next(5000, 10000));

                        contThinkCount = 0;

                        RightFork.Put();
                        LeftFork.Put();
                    }
                    else
                    {
                        // else put the left fork back on the table
                        LeftFork.Put();
                    }
                }
            }

            Think();
        }

        public void Think()
        {
            this.State = PhilosopherState.Thinking;
            Console.WriteLine("^^*^^ {0} is thinking...on {1}", Name, Thread.CurrentThread.Priority.ToString());
            Thread.Sleep(rand.Next(2500,20000));
            contThinkCount++;

            if (contThinkCount > StarvationThreshold)
            {
                Console.WriteLine(":ooooooooooooooooooooooooooooooooooooooooooooooo: {0} is starving", Name);
            }

            Eat();
        }

        private bool TakeForkInLeftHand()
        {
            return LeftFork.Take(Name);
        }

        private bool TakeForkInRightHand()
        {
            return RightFork.Take(Name);
        }

    }




    enum ForkState { Taken, OnTheTable }
    

    class Fork
    {
        public string ForkID { get; set; }
        public ForkState State { get; set; }
        public string TakenBy { get; set; }

        public bool Take(string takenBy)
        {
            lock (this)
            {
                if (this.State == ForkState.OnTheTable)
                {
                    State = ForkState.Taken;
                    TakenBy = takenBy;
                    Console.WriteLine("||| {0} is taken by {1}", ForkID, TakenBy);
                    return true;
                }

                else
                {
                    State = ForkState.Taken;
                    return false;
                }
            }
        }

        public void Put()
        {
            State = ForkState.OnTheTable;
            Console.WriteLine("||| {0} is place on the table by {1}", ForkID, TakenBy);
            TakenBy = String.Empty;   
        }
    }



    class Table
    {
        internal static Fork Platinum = new Fork () { ForkID = "Platinum Fork", State = ForkState.OnTheTable};
        internal static Fork Gold = new Fork() { ForkID = "Gold Fork", State = ForkState.OnTheTable };
        internal static Fork Silver = new Fork() { ForkID = "Silver Fork", State = ForkState.OnTheTable };
        internal static Fork Wood = new Fork() { ForkID = "Wood Fork", State = ForkState.OnTheTable };
        internal static Fork Plastic = new Fork() { ForkID = "Plastic Fork", State = ForkState.OnTheTable };
    }
}

Sleeping Barber – C#

The sleeping barber is one of the problems which is used to demonstrate the correct thread notification mechanism. Here’s the a sample code for the sleeping barber problem in C# for .NET 4.0. Keep in mind that this code is optimized for the .NET 4.0 not for prior versions. You have concurrent collections in .NET 4.0.

 

using System;
using System.Threading;
using System.Collections.Concurrent;
using Microsoft.ConcurrencyVisualizer.Instrumentation;

namespace SleepingBarber
{
    class Program
    {
        internal static AutoResetEvent customerEvent = new AutoResetEvent(false);

        // no explict locks needed as it is a ConcurrentQueue > feature in .NET 4.0
        internal static ConcurrentQueue<Customer> queue = new ConcurrentQueue<Customer>();

        static void Main(string[] args)
        {
            Random rand = new Random();

            // make the barber background so the program can exit once the main thread is finished.
            // this does not impact the thread priority.
            new Thread(Barber.CutHair) { IsBackground = true, Name = "Barber" }.Start();

            Thread.Sleep(100);

            Thread.CurrentThread.Name = "Main";
            // creating 25 customers in random order
            for (int i = 0; i <25; i++)
            {
                // temp is used to avoid the captured variable problem
                int temp = i;
                Thread.Sleep(rand.Next(600, 2000));
                Customer c = new Customer() {Name = "Customer " + temp };
                queue.Enqueue(c);

                if (queue.Count == 1)
                {
                    Customer.WakeUpBarber();
                }
            }

            Console.ReadKey();
        }
    }

    class Customer
    {
        public string Name { get; set; }

        internal static void WakeUpBarber()
        {
            Program.customerEvent.Set();
        }
    }

    class Barber
    {
        internal static void CutHair()
        {
            while (!Program.queue.IsEmpty)
            {
                Customer c;

                // time to cut the hair is 1 sec
                Thread.Sleep(1000);

                // after cutting hair barber removes him from the queue
                if (Program.queue.TryDequeue(out c))
                {
                    Console.WriteLine("Done hair cutting to {0}", c.Name);
                }
                else
                {
                    // this will never happen in this scenario as only one barber is here
                    Console.WriteLine(" 😦 customer is not going out ...");
                }
            }

            Console.WriteLine("Going to sleep.... grr...err....");
            GoToSleep();
        }

        private static void GoToSleep()
        {
            using (Markers.EnterSpan("wait start"))
            {
                Program.customerEvent.WaitOne();
                Console.WriteLine("Waking up..Oh ! Customer arrived..");
            }
            CutHair();
        }
    }
}

Simple Client–Server in C#

 

This is a very simplest client server model which is only to demonstrate the client server working model. And a simple program to learn threads in C#.

Client connects to the server and then server delivers a unique number to each client by simply incrementing a static variable. The increment is locked for thread safety.

Code for the server.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;

namespace ConsoleServer
{
    class Program
    {
        static TcpListener server;
        static int count = 0;
        static readonly object o = new object();

        static void Main(string[] args)
        {
            IPHostEntry host = Dns.GetHostEntry("localhost");
            IPAddress ip = new IPAddress(host.AddressList.First().GetAddressBytes());

            server = new TcpListener(ip, 2000);
            server.Start();

            bool exit = false;

            Console.WriteLine("Server started on port 2000");

            while (!exit)
            {
                // here pending requests are in a queue.
                if (server.Pending())
                {
                    new Thread(Program.ServerService).Start();
                }
            }

            Console.ReadKey();
            server.Stop();

        }

        public static void ServerService()
        {
            Socket socket = server.AcceptSocket();

            Console.WriteLine("Connected " + socket.RemoteEndPoint);

            Stream stream = new NetworkStream(socket);
            StreamWriter writer = new StreamWriter(stream);
            StreamReader reader = new StreamReader(stream);

            writer.AutoFlush = true;
        
            writer.Write("Initial Number {0}",GetNumber());

            bool client = false;

            new Thread(() =>
            {
                while (!client)
                {
                    string s = "";
                    s = reader.ReadLine();

                    if (s == "req")
                    {
                        writer.Write(GetNumber());
                        writer.Flush();
                    }
                }
            }).Start();
        }

        private static int GetNumber()
        {
            // here sleep time gets activated after one client leaves the lock block.
            // so if a first client gets short long sleep time and second one gets short, still the second one has to wait till the first one finishes.

            Random r = new Random();
            int time = r.Next(200, 2000);
            Console.WriteLine("Sleeping time : {0}", time);

            lock(o)
            {
                Thread.Sleep(time);
                return ++count;
            }
        }
    }
}


Code for the client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace ConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("localhost", 2000);

            Stream stream = client.GetStream();
            StreamReader reader = new StreamReader(stream);

            Console.WriteLine(reader.ReadLine());

            stream.Flush();
            
            new Thread(() =>
             {
                 Console.WriteLine("New Request {0} ", reader.ReadLine());

                 Console.WriteLine("Waiting for exit");
                 Console.ReadKey();
             }).Start();

 

            while (true)
            {
                string req = Console.ReadLine();

                if (req == "new")
                {
                    StreamWriter writer = new StreamWriter(stream);
                    writer.Write(req);
                    writer.Flush();
                }
            }
            client.Close();

        }
    }
}

Year 2011 – Thuruinhttp @ WordPress

The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog.

Here’s an excerpt:

A New York City subway train holds 1,200 people. This blog was viewed about 3,800 times in 2011. If it were a NYC subway train, it would take about 3 trips to carry that many people.

Click here to see the complete report.

Computer Plaza in Colombo – Secrets

 

I do not know whether all who sell electronics are like this. I really do not know. But I got to know one of the famous plaza in Colombo is like this.

This is a true story. For their safety and for the promise I made on the people who revealed this information I’m not mentioning any names here.

The well formed computer hardware fortress in Colombo. Always crowded. People look for computers, peripherals, software, gaming gadgets and even hand bags…..

We think there are plenty of shops with different owners. Of course they are different but the whole bunch of shops have only 8 owners at the very top level.

There are plenty companies/places in China, Thailand and Malaysia who produce electronics. In those countries small chip manufacturing is a home business. (some thing like rope knitting or wood sculpturing in our country). Most of the small electronic gadgets sold in the plaza are from those markets with the fake label of a big company.

You can’t buy a single genuine gadget anywhere here. (told by a person who works in a shop for 3 years)

The secret is when they import things here, all the owners discuss and fix a maximum prize tag for each gadget. Minimum is up to the owner on his/her own risk. Normally they don’t used to have the meetings in Srilanka. Most of the owners are also not in Srilanka.

When they fix a price normally that is 2 or 3 times bigger than the actual cost. (if you buy something for 3000 the actual value is very less than 1000). And each shop has it’s own technique of selling the gadget. If one say they can sell a gadget for 10K without any warranty and they say with 1 year warranty they can give you for 14K. Go for the one without the warranty

Because they don’t change anything, just the same thing. They just want to sell you. They know that most of the time the gadget works fine for 1 year. In this case the person goes for the warranty is doomed.

Even if you are going for the guaranteed gadgets, make sure to get a signed bill buy the manager with his name (not by the sales person) with the written statement for the warranty.

And when it comes to laptops, some shops have direct dealerships with the real companies, but again locally they play their game.

A laptop of any brand with core i3 2nd gen processor with other decent configuration will not cost more than 30K SLR. – (another sales person a from a shop)

When they import a laptop here; most of the shops reconfigure the laptops. If a sales person tells you that he can prize a laptop for 50K and with another 2 or 4 GB of additional RAM or with a more higher capacity HDD he can give that for 55K, then please do double check.

Because if a sales person tells like this, it is most likely to be that the laptop really comes with  more memory or with a higher capacity HDD. When he says if you buy this another 4GB RAM or 500 GB HDD is just for 2 ~ 3K we immediately go for that. A selling trick to cheat on the prizes.

Normally take the serial number / model number of the laptop and check in the specific brand’s official site whether there is really an official model is available. If so then check the configuration carefully.

“They mostly interchange the parts” – (a person works in a service shop)

Apart from this, the place is well known for the money transfers and foreign exchange selling and mainly for buying. You can buy almost all the currencies here, is a very hot business. I do not know whether they have any tricks on this as well. Because to do this you have to go through a trusted party.

Finally you can ask how do I know all these things ? I purchased and fooled by them many times as like you. But still no use. We are not reluctant to pay, but why they cheat? If they can do a genuine business still people will buy things.

Do you believe that I haven’t spent a single penny on collecting this information?

Concurrent Collections and TPL–.NET 4.0

TPL in .NET 4.0 is a cool thing when programming modern PCs which have CPUs with more than one core. CPUs with many cores are popular these days because hardware vendors make CPUs with many cores to cater the Moore’s Law. 🙂 Or they might have tired of shrinking the transistor size up to 32nm. There are smaller versions than that..

Task Parallel Library’s (TPL’s) Task.Factory.StatNew( () => {..} is the .NET 4.0’s replacement for the Thread.QueueUserWorkItem() and asynchronous delegates. In this case TPL is more close to the asynchronous delegates and also it is documented that; TPL can leverage the underlying CPU cores more effectively than asynchronous delegates.

But in the documentation TPL considered as a library for the parallel programming.

And we also have Concurrent Collections in System.Collections.Concurrent namespace which contains the thread safe versions of the normal collections. So this makes easy that we do not need to handle explicit locks while handling the collections from different threads.

Concurrent Collections are slower compared to normal collections and little different, but thread safe. Even in the documentation and MSDN samples concurrent collections are mentioned in the parallel programming paradigm, not in a multi threaded application’s view.

I had some doubt on this, whether is it OK to use them in multi threaded environment; and raised a question in the MSDN, The thread seems to be useful and interesting.

I didn’t repost the question , answers and the code in my blog, as you can see them here