Creating Single Instance Applications: Working with Mutexes

Applications are our bread and butter. There are essentially two instances in which an application can be run: Single Instance and Multiple Instances.

Single Instance Applications

Single Instance Applications means that only one instance can be run at any given point in time. In other words, this means that you cannot run the same application simultaneously.

Multiple Instance Applications

A Multiple Instance Application can be run simultaneously; for example, Notepad. You can have as many instances of Notepad running at any given time as you want.


According to MSDN, you can use a Mutex object to provide exclusive access to a resource. The Mutex class uses more system resources than the Monitor class, but it can be marshaled across application domain boundaries, it can be used with multiple waits, and it can be used to synchronize threads in different processes.


According to Wikipedia, a semaphore is a variable or abstract data type that is used for controlling access, by multiple processes, to a common resource in a concurrent system such as a multiprogramming operating system.

A trivial semaphore is a plain variable that is changed (for example, incremented or decremented, or toggled) depending on programmer-defined conditions. The variable then is used as a condition to control access to some system resource.


Here is a nice exercise on working with threads.

Our Application

Start Visual Basic and create a new Console application. Add the following code to your application:

Imports System.Threading
Module Module1

   Sub Main()
      Dim OneMutex As Mutex = Nothing
      Const MutexName As String = "RUNMEONLYONCE"

         OneMutex = Mutex.OpenExisting(MutexName)
      Catch ex As WaitHandleCannotBeOpenedException

      End Try

      If OneMutex Is Nothing Then
         OneMutex = New Mutex(True, MutexName)
      End If

      Console.WriteLine("Our Application")

   End Sub

End Module

A Mutex object gets created and then later on we check whether this Mutex is currently in use. If it is in use, we exit; otherwise, we run the application normally.


This is just one example on how to create a single instance application though Visual Basic.

About the Author

Hannes DuPreez

Hannes du Preez is a Microsoft MVP for Visual Basic for the eighth consecutive year. He loves technology and loves Visual Basic. He has a lot of experience in .NET and loves to share his love, pain and musings about Visual Basic

Related Articles


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date