11.10.2019

C#: Running a program in a single instance

Sometimes you need to run your program just in a single instance. For example it can happen when you use some resources which can not be shared (devices, databases or something else). In this case the following method of running your program can help:
class Program
{
     static void Main(string[] args)
     {
          bool existed;
          // obtaining application GIUD
          string guid = Marshal.GetTypeLibGuidForAssembly(Assembly.GetExecutingAssembly()).ToString();

          Mutex mutexObj = new Mutex(true, guid, out existed);

          if (existed)
          {
               Console.WriteLine("Application is already running");
          }
          else
          {
               Console.WriteLine("This is the first instance of this application.");
          }

          Console.ReadLine();
     }
}

Комментариев нет:

Отправить комментарий