Saturday, March 23, 2013

Mutex-Simply



Mutex - I just came across a very simple definition and example of mutex from Threading in C#, by Joe Albahari, so I just thought of sharing it.
A 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\.


Note : For more in depth knowledge you can go to link

Saturday, February 23, 2013

Unit Test not running in VS 2010 after installation of VS2012.

Many of developers might have experienced this scenario of unit test not getting executing in VS 2010 after installation of VS2012 next to VS2010.

The simple solution to this problem is to install VS2010 SP1.

For more insight on the issue have a look on this link

Hope this helps :)

Sunday, January 20, 2013

Prime Numbers Up to a range K

In order to find all of the prime numbers up to a range  K, we can use Sieve of  Eratosthene.Please find below the algorithm:-


isPrime[0] = false
isPrime[1] = false
for i = 2 to K do
    isPrime[i] = true
for i = 2 to sqrt(K) do
    if isPrime[i] then
        for j = i * i to K with step i do
            isPrime[j] = false
where you can consider isPrime as array of bool up to K. 
I find out about this interesting algorithm during a programming contest and it can be useful for fast calculation of all prime numbers up to a particular range.
For further reading , please refer to below link:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes