Archive

Archive for the ‘C#’ Category

Factory pattern Vs Abstract Factory pattern


Factory: A factory that creates objects that derive from a particular base class.

Abstract factory: A factory that creates other factories, and these factories in turn create objects derived from base classes. You do this because you often don’t just want to create a single object (as with Factory method) – rather, you want to create a collection of related objects.

Real Life Example. (Easy to remember)

Factory

Imagine you are constructing a house and you approach a carpenter for a door. You give the measurement for the door and your requirements, and he will construct a door for you. In this case, the carpenter is a factory of doors. Your specifications are inputs for the factory, and the door is the output or product from the factory.

Abstract Factory

Now, consider the same example of the door. You can go to a carpenter, or you can go to a plastic door shop or a PVC shop. All of them are door factories. Based on the situation, you decide what kind of factory you need to approach. This is like an Abstract Factory.

 

Categories: C# Tags: ,

The Object Class


The Object class is a special type that is the base class for all other classes and types, including the value types. It defines a set of methods that are therefore inherited by every other type that is defined within the .NET framework class library.

What is the Object Class?

The Object class, held in the System namespace, is the base class for all classes and data types, including the value types. It is the class at the root of the .NET framework class library’s entire type hierarchy.

System.Object defines several public and protected methodsthat, due to inheritance, are automatically made available to all .NET classes, structures and types, including any classes or structures that you create yourself. If you create a class with no base class specified, it will implicitly derive functionality from Object.

Often developers overlookthe Object class. However, its importance is significant and the complexities if its members should be understood.

object = Object

The C# programming language declares a data type named “object”. This type is simply an alias for System.Object and so the two terms are interchangeable; they differ in capitalisation but not functionality.

Object methods

The Object class defines seven base methods. Of these, five are public methods that are available to be called by external objects. The remaining two methods are protected. These are only accessible internally and to derived classes. Each of the methods is described in the following sections.

Public Methods


Equals Method

The Equals method is used to compare two objects to determine if they are equal. The comparison of the objects depends upon their types. For the value types, a bit-by-bit comparison of the two values is made. If they are a perfect match, the method returns true. If not, the method returns false.

When comparing reference types, the values of the two references are compared. Only when both references are pointing to the same object does the method return true. If the properties of two objects are a perfect match but the references are different, the method returns false.

The Equals method can be overridden in a subclass. This permits the behaviour to be changed so that it is more appropriate. For example, in the case of the string data type, Equals is overridden so that a comparison of two strings can be made as though they were value types. Even when the two strings contain different references, if the underlying characters match, the method returns true.

string s1 = "Hello";
string s2 = "Hello";
bool result = s1.Equals(s2); // result = true

The Equals method is available in two forms. The instance version is shown in the above example. In this case, the method requires a single parameter containing the item to be compared to the invoking object. A static version of the method is also available. This requires two parameters, one for each of the items to be compared. The above example could therefore be rewritten as:

string s1 = "Hello";
string s2 = "Hello";
bool result = string.Equals(s1, s2); // result = true

When overriding the behaviour of the Equals method, there are several rules that must be followed to ensure correct operation. These are:

  • A call to x.Equals(x), where “x” is a variable of the class in question, must return true. The only exception to this rule is in the comparison of floating point data, where you may decide that a variable containing NaN (not a number) is not equivalent to itself. NB: Interestingly, the floating point types in the .NET framework return true when comparing NaN to NaN using the Equals method, but false when using the == operator. The == operator matches theIEC 60559:1989 specification whilst the Equals method does not.
  • A call to x.Equals(y) must return the same result as a call to y.Equals(x).
  • The expression “x.Equals(y) && y.Equals(z)” must only return true if x.Equals(z) returns true.
  • If x and y are not modified, successive calls to x.Equals(y) must return consistent results.
  • A call to x.Equals(null) must return false.
  • If the == operator is overloaded, the Equals method must be overridden to provide matching functionality, except in the case of floating point value types.
  • If Equals is overridden, the GetHashCode method must also be overridden for compatibility. Otherwise,Hashtables may function incorrectly.
  • If a class implements the IComparable interface, the Equals method should be overridden.
  • The Equals method must not throw exceptions.

GetHashCode Method

The GetHashCode method provides an algorithm to generate a hash code for an object. Hash codes are used when creatinghash tables to permit objects to be found quickly in large sets of data. The GetHashCode method is used by the Hashtable collection class for this purpose.

The GetHashCode method returns an integer containing the hash code for an object. The value is not unique and should not be used as an identifier or for any purposes other than when using a hashing function. This is particularly relevant when using multiple versions of the .NET framework as the hashing algorithms for classes vary between versions, leading to different results for identical objects.

You can see examples of the return values by executing the following code. The results shown are generated using version 3.5 of the .NET framework and may differ from those you see.

int i = 10;
float f = 10;
string s = "Hello";
int result;
result = i.GetHashCode(); // result = 10
result = f.GetHashCode(); // result = 1092616192
result = s.GetHashCode(); // result = -694847

The GetHashCode method can be overridden. When doing so, the following guidelines should be followed:

  • If GetHashCode is overridden, the Equals method must also be overridden for compatibility. Otherwise, Hashtables may function incorrectly.
  • The value returned from the hashing algorithm must be appropriate for value types. Two values that would be considered equal when using the Equals method must return the same hash code.
  • The hash codes generated by the algorithm should be well distributed amongst the available range of integer return values. If the algorithm produces many duplicates or similar values, the performance of Hashtables will be impacted.
  • The hashing algorithm should be as fast and efficient as possible to avoid performance issues with Hashtables.
  • The GetHashCode method must not throw exceptions.

GetType Method

The GetType method simply returns the type of the object that invokes it. This is useful when using polymorphismtechniques as the type of the underlying object can be identified, even if held in a variable declared as another type. For example, if “Dog” is a subclass of “Animal” and a Dog object is being held in an Animal variable, the type returned will still be Dog. The method is also used for reflection.

The type is returned in a System.Type object. A detailed description of the System.Type class is beyond the scope of this article. For demonstration purposes we will simply output a string representation of the type to the console.

string s = "Hello";
Console.WriteLine(s.GetType()); // Outputs "System.String"
object o = s;
Console.WriteLine(o.GetType()); // Outputs "System.String"

ReferenceEquals Method

The ReferenceEquals method is a static member of the Object class. It is used with reference types to determine if two instances of a class contain the same reference. If the references are the same, the method returns true. If the references are different, the method returns false, even if the values of the two instances match. If the two items to be compared are both null, the resultant value is true. If they are two value types, the result is always false.

The method is called with two parameters, each holding one of the references to be compared.

object o1 = new object();
object o2 = new object();
object o3 = o1;
bool result;
result = object.ReferenceEquals(o1, o2); // result = false
result = object.ReferenceEquals(o1, o3); // result = true
int i1 = 1;
int i2 = 1;
result = object.ReferenceEquals(i1, i2); // result = false

ToString Method

 

The ToString method is probably the most well-known and used member of the Object class. This method returns a human-readable, string representation of the current object. The default behaviour is to return the fully qualified name of the object’s type. However, this can be overridden to provide a more useful value, as in the case of thenumeric types where the ToString method is overridden and overloaded to allow the creation of formatted numeric strings.

The base version of ToString provided by the Object class accepts no parameters.

object o = new object();
Console.WriteLine(o.ToString()); // Outputs "System.Object"

Protected Methods


Finalize Method

The Finalize method is the first protected method of the Object class that we will consider. This method permits objects to clean up any resources and perform any other activities that are required before an object that is no longer required is reclaimed by the garbage collector. Finalizers in C# are declared as destructors.

The Finalize method cannot be overridden and may not be called during the normal execution of a program. The method is called automatically after an object is no longer accessible, due to all references to it being removed or going out of scope. However, there is no guarantee of the exact execution time of the Finalize method and certainly no assumption that it will run immediately should be made. It is also possible that the finalizer will not run at all if another Finalize method is blocked indefinitely or if the program terminates abnormally.

If two objects become inaccessible at the same time, there is no guarantee of the order in which their finalizers will be called. This is still the case when one of the objects refers to the other.

Classes must implement a destructor when they use unmanaged resources such as database connections or file handles. These resources cannot be reclaimed by the garbage collector and will otherwise not be correctly released. However, in these cases, the class should also implement the IDisposable interface.

MemberwiseClone Method

The MemberwiseClone method is used to create a shallow copy of an object. A shallow copy of an object contains the same values and references as the original. For value type members, this is a bitwise copy of the member data. For reference type members the reference only is copied, meaning that the copy and the original are references to the same object. The method is called with no parameters and returns the cloned object as a System.Object that may be cast to the correct type as required.

Categories: C# Tags:

Association, Aggregation, Composition


en we have only one relationship between objects, that is called Association. Aggregation and Composition both are specialized form of Association. Composition is again specialize form of Aggregation.

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.

Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically delete.

Categories: C# Tags: , ,

Difference between String and StringBuffer/StringBuilder


Well, the most important difference between String and StringBuffer/StringBuilder is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.

By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is “If String is immutable then how am I able to change the contents of the object whenever I wish to?” . Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.

So suppose you declare a String object:

String myString = “Hello”;

Next, you want to append “Guest” to the same String. What do you do?

myString = myString + ” Guest”;

When you print the contents of myString the output will be “Hello Guest”. Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.

Now isn’t that a performance issue?

Yes, it definitely is.

Then how do you make your string operations efficient?

By using StringBuffer or StringBuilder.

How would that help?

Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.

Finally, whats the difference between StringBuffer and StringBuilder?

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence ofsynchronization.

Categories: C# Tags: , ,

Lock, Monitor, Mutex, Semaphore

April 17, 2012 1 comment

Locking

Exclusive locking is used to ensure that only one thread can enter particular sections of code at a time. The two main exclusive locking constructs are lock and Mutex. Of the two, the lock construct is faster and more convenient.Mutex, though, has a niche in that its lock can span applications in different processes on the computer.

Let’s start with the following class:

class ThreadUnsafe
{
  static int _val1 = 1, _val2 = 1;

  static void Go()
  {
    if (_val2 != 0) Console.WriteLine (_val1 / _val2);
    _val2 = 0;
  }
}

This class is not thread-safe: if Go was called by two threads simultaneously, it would be possible to get a division-by-zero error, because _val2 could be set to zero in one thread right as the other thread was in between executing the if statement and Console.WriteLine.

Here’s how lock can fix the problem:

class ThreadSafe
{
  static readonly object _locker = new object();
  static int _val1, _val2;

  static void Go()
  {
    lock (_locker)
    {
      if (_val2 != 0) Console.WriteLine (_val1 / _val2);
      _val2 = 0;
    }
  }
}

Only one thread can lock the synchronizing object (in this case, _locker) at a time, and any contending threads areblocked until the lock is released. If more than one thread contends the lock, they are queued on a “ready queue” and granted the lock on a first-come, first-served basis (a caveat is that nuances in the behavior of Windows and the CLR mean that the fairness of the queue can sometimes be violated). Exclusive locks are sometimes said to enforceserialized access to whatever’s protected by the lock, because one thread’s access cannot overlap with that of another. In this case, we’re protecting the logic inside the Go method, as well as the fields _val1 and _val2.

Monitor.Enter and Monitor.Exit

C#’s lock statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit, with atry/finally block. Here’s (a simplified version of) what’s actually happening within the Go method of the preceding example:

Monitor.Enter (_locker);
try
{
  if (_val2 != 0) Console.WriteLine (_val1 / _val2);
  _val2 = 0;
}
finally { Monitor.Exit (_locker); }

Calling Monitor.Exit without first calling Monitor.Enter on the same object throws an exception.

Mutex

Mutex is like a C# lock, but it can work across multiple processes. In other words, Mutex can be computer-wideas well as application-wide.

Acquiring and releasing an uncontended Mutex takes a few microseconds — about 50 times slower than a lock.

With a Mutex class, you call the WaitOne method to lock and ReleaseMutex to unlock. Closing or disposing aMutex automatically releases it. Just as with the lock statement, a Mutex can be released only from the same thread that obtained it.

A common use for a cross-process Mutex is to ensure that only one instance of a program can run at a time. Here’s how it’s done:

class OneAtATimePlease
{
  static void Main()
  {
    // Naming a Mutex makes it available computer-wide. Use a name that's
    // unique to your company and application (e.g., include your URL).

    using (var mutex = new Mutex (false, "oreilly.com OneAtATimeDemo"))
    {
      // Wait a few seconds if contended, in case another instance
      // of the program is still in the process of shutting down.

      if (!mutex.WaitOne (TimeSpan.FromSeconds (3), false))
      {
        Console.WriteLine ("Another app instance is running. Bye!");
        return;
      }
      RunProgram();
    }
  }

  static void RunProgram()
  {
    Console.WriteLine ("Running. Press Enter to exit");
    Console.ReadLine();
  }
}

If running under Terminal Services, a computer-wide Mutex is ordinarily visible only to applications in the same terminal server session. To make it visible to all terminal server sessions, prefix its name with Global\.

Semaphore

A semaphore is like a nightclub: it has a certain capacity, enforced by a bouncer. Once it’s full, no more people can enter, and a queue builds up outside. Then, for each person that leaves, one person enters from the head of the queue. The constructor requires a minimum of two arguments: the number of places currently available in the nightclub and the club’s total capacity.

A semaphore with a capacity of one is similar to a Mutex or lock, except that the semaphore has no “owner” — it’sthread-agnostic. Any thread can call Release on a Semaphore, whereas with Mutex and lock, only the thread that obtained the lock can release it.

There are two functionally similar versions of this class: Semaphore and SemaphoreSlim. The latter was introduced in Framework 4.0 and has been optimized to meet the low-latency demands of parallel programming. It’s also useful in traditional multithreading because it lets you specify acancellation token when waiting. It cannot, however, be used for interprocess signaling.

Semaphore incurs about 1 microsecond in calling WaitOne or ReleaseSemaphoreSlim incurs about a quarter of that.

Semaphores can be useful in limiting concurrency — preventing too many threads from executing a particular piece of code at once. In the following example, five threads try to enter a nightclub that allows only three threads in at once:

class TheClub      // No door lists!
{
  static SemaphoreSlim _sem = new SemaphoreSlim (3);    // Capacity of 3

  static void Main()
  {
    for (int i = 1; i <= 5; i++) new Thread (Enter).Start (i);
  }

  static void Enter (object id)
  {
    Console.WriteLine (id + " wants to enter");
    _sem.Wait();
    Console.WriteLine (id + " is in!");           // Only three threads
    Thread.Sleep (1000 * (int) id);               // can be here at
    Console.WriteLine (id + " is leaving");       // a time.
    _sem.Release();
  }
}

1 wants to enter
1 is in!
2 wants to enter
2 is in!
3 wants to enter
3 is in!
4 wants to enter
5 wants to enter
1 is leaving
4 is in!
2 is leaving
5 is in!

If the Sleep statement was instead performing intensive disk I/O, the Semaphore would improve overall performance by limiting excessive concurrent hard-drive activity.

Semaphore, if named, can span processes in the same way as a Mutex.

Categories: C# Tags: , , ,

ThreadPool


A thread pool takes away all the need to manage your threads – all you have to do is essentially say “hey! someone should go do this work!”, and a thread in the process’ thread pool will pick up the task and go execute it. And that is all there is to it. Granted, you still have to keep threads from stepping on each other’s toes, and you probably care about when these ‘work items’ are completed – but it is at least a really easy way to queue up a work item.

In fact, working with the ThreadPool is so easy, I’m going to throw all the code at you at once. Below is a pretty simple test app that gives 5 (or NumThreads) work items to the ThreadPool, waits for them all to complete, and then prints out all the answers. I will walk through the code step by step below:

 

using System;
using System.Threading;namespace ThreadPoolTest
{
class Program
{
private const int NumThreads = 5;

private static int[] inputArray;
private static double[] resultArray;
private static ManualResetEvent[] resetEvents;

private static void Main(string[] args)
{
inputArray = new int[NumThreads];
resultArray = new double[NumThreads];
resetEvents = new ManualResetEvent[NumThreads];

Random rand = new Random();
for (int s = 0; s < NumThreads; s++)
{
inputArray[s] = rand.Next(1,5000000);
resetEvents[s] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), (object)s);
}

Console.WriteLine(“Waiting…”);

WaitHandle.WaitAll(resetEvents);

Console.WriteLine(“And the answers are: “);
for (int i = 0; i < NumThreads; i++)
Console.WriteLine(inputArray[i] + ” -> ” + resultArray[i]);
}

private static void DoWork(object o)
{
int index = (int)o;

for (int i = 1; i < inputArray[index]; i++)
resultArray[index] += 1.0 / (i * (i + 1));

resetEvents[index].Set();
}
}
}

 

We have three arrays at the top of the program: one for input to the work items (inputArray), one for the results (resultArray), and one for the ManualResetEvents (resetEvents). The first two are self explanatory, but what is aManualResetEvent? Well, it is an object that allows one thread to signal another thread when something happens. In the case of this code, we use these events to signal the main thread that a work item has been completed.

So we initialize these arrays, and then we get to a for loop, which is where we will be pushing out these work items. First, we make a random value for the initial input (cause random stuff is always more fun!), then we create aManualResetEvent with its signaled state initially set to false, and then we queue the work item. Thats right, all you have to do to push a work item out for the ThreadPool to do is call ThreadPool.QueueUserWorkItem.

So what are we queuing here? Well, we are saying that a thread in the thread pool should run the method DoWork, with the argument s. Any method that you want to queue up for the thread pool to run needs to take one argument, an object, and return void. The argument will end up being whatever you passed in as the second argument to theQueueUserWorkItem call – and in this case is the ‘index’ of this work item (the index in the various arrays that it needs to work with). And it makes sense that the method would have to return void – because it isn’t actually returning ‘to’ anything, it is running out there all on its own as a separate thread.

So what are we doing in this DoWork function? Not that much in this case, just a simple summation. The important part is the very last call of the function, which is hit when all the work for this work item is done –resetEvents[index].Set(). This triggers the ManualResetEvent for this work item – signaling the main thread that the work is all done here.

Back up in main thread land, after it has pushed all these work items onto the ThreadPool queue, we hit the very important call WaitHandle.WaitAll(resetEvents). This causes the main thread to block here until all theManualResetEvent objects in the resetEvents array signal. When all of them have signaled, that means that all the work units have been completed, and so we continue on and print out all the results. The results change because we are seeding with random values, but here is one example output:

 

Waiting…
And the answers are:
3780591 -> 0.991001809831479
3555614 -> 0.991163782231558
2072717 -> 0.989816715560308
2264396 -> 0.989982111762391
544144 -> 0.99066981542858

 

Pretty simple, eh? There are a couple things to note, though. The default thread pool size for a process is 25 threads, and while you can change this number, this resource is not infinite. If all of the threads in the pool are currently occupied with other tasks, new work items will be queued up, but they won’t get worked on until one of the occupied threads finishes its current task. This generally isn’t a problem unless you are giving the pool very large quantities of work. And really, you should never assume that a task is executed immediately after you queue it, because there is no guarantee of that at all.

That’s it for this intro to thread pools in C#. If there are any questions, leave them below – especially if they push on the more advanced aspects of threads and thread pools (cause then I’ll have an excuse to write some more threading tutorials!).

Categories: C# Tags:

EventWaitHandler: AutoResetEvent vs. ManualResetEvent


WaitHandler
Threads can communicate using WaitHandlers by signaling. Mutex, Semapore and EventWaitHandle are derived from WaitHandle class.

EventWaitHandle 
There are two types of EventWaitHandlers. AutoResetEvent and ManualResetEvent. AutoResetEvent lets one waiting thread at a time when Set() is called but ManualResetEvent lets all waiting threads to pass by when Set() is called. ManualResetEvent starts blocking when Reset() is called.

AutoResetEvent
This acts like a turnstile which lets one at a time. When a thread hits WaitOne(), it waits till some other thread calls Set(). Take a look at the following picture. Thread1, Thread2 and Thread3 are waiting after calling WaitOne(). For every Set() call from another thread, one thread will pass the turnstile.

I have created a simple application to test this. There are two buttons to span a thread DoWork. DoWork has WaitOne call and it blocks threads. Third button calls Set() to release one thread at a time. Click first two buttons to span thread and click third button twice to release blocked threads.

private EventWaitHandle wh = new AutoResetEvent(false);
private void DoWork()
{
    Console.WriteLine(Thread.CurrentThread.Name + ": Waiting for Set() notification");
    // Wait for notification
    //
    wh.WaitOne();
    Console.WriteLine(Thread.CurrentThread.Name + ": Notified");
}
private void buttonCreateThreadOne_Click(object sender, EventArgs e)
{
    Thread a = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    a.Name = "A";
    a.Start();
}
private void buttonCreateSecondThread_Click(object sender, EventArgs e)
{
    Thread b = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    b.Name = "B";
    b.Start();
}
private void buttonReleaseOneThread_Click(object sender, EventArgs e)
{
    wh.Set();
}

 

Please note that the code after WaitOne call in DoWork is not thread safe. A call to Set will let next waiting thread to enter even the first thread is still executing the code.

 

ManualResetEvent
This is like a gate which lets more than one at a time. When a thread hits WaitOne(), it waits till someother thread calls Set(). Take a look at the following picture. Thread1, Thread2 and Thread3 are waiting after calling WaitOne(). When Set is called from another thread, all waiting thereads will pass the gate.

Code snippet to illustrate the above.

private void buttonFirstThread_Click(object sender, EventArgs e)
{
    Thread a = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    a.Name = "A";
    a.Start();
}
private void buttonSecondThread_Click(object sender, EventArgs e)
{
    Thread b = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    b.Name = "B";
    b.Start();
}
private void buttonCallSet_Click(object sender, EventArgs e)
{
    wh.Set();
}
private void buttonCallReset_Click(object sender, EventArgs e)
{
    wh.Reset();
}
Categories: C#, WPF Tags: ,
%d bloggers like this: