Showing posts with label Assembly. Show all posts
Showing posts with label Assembly. Show all posts

Saturday, June 16, 2018

How to make sure only single instance of your application is running?


There are many ways to keep running single instance of your application. In this article i'll explain how you can use Mutex and GetProcesses to keep single instance of your application.


Mutex  



Mutex is threading synchronisation mechanism. Named mutex works across multiple applications. I've explained more about Mutex in my previous article under Threading. Below example demonstrated how mutex is used to keep single instance of your console application.

Code –
class Program
{
    static void Main(string[] args)
    {
        bool isFirstInstance;
        using (Mutex mutex = new Mutex(true, "MyApp", out isFirstInstance))
        {
            if (isFirstInstance)
            {
                Console.WriteLine("Welcome, Running first instance of MyApp");
                Console.Read();
            }
            else
            {
                Console.WriteLine("One instance of MyApp is already running.");
                Console.Read();
            }
        }
    }
}

Output –



Similar code you can do for WPF application.

Code –
public partial class App : Application
{
    private static Mutex mutex = null;
    protected override void OnStartup(StartupEventArgs e)
    {
        bool isFirstInstance;
        mutex = new Mutex(true, "MyWPFApp", out isFirstInstance);
        if (isFirstInstance)
        {
            MessageBox.Show("Welcome, Running first instance of MyWPFApp", "Info");
            MainWindow window = new MainWindow();
            window.Show();
        }
        else
        {
            MessageBox.Show("One instance of MyWPFApp is already running.", "Info");
            Application.Current.Shutdown();
        }
           

        base.OnStartup(e);
    }
}

Output –



GetProcesses  


One more way to check single instance of your running application using Get Processes. See below example.

static void Main(string[] args)
{
    //get process count of your application
    if (System.Diagnostics.Process.GetProcessesByName(
        System.IO.Path.GetFileNameWithoutExtension(
            System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1)
    {
        Console.WriteLine("One instance is already running so closing this instance");
        Console.Read();
        System.Diagnostics.Process.GetCurrentProcess().Kill();
    }
    else
    {
        Console.WriteLine("Welcome, Running first instance.");
        Console.Read();
    }

}





You can download code from Gist.

Thank you for reading this article. Please leave your feedback in comments below.

Reference –

See also –

Sunday, July 10, 2016

How to create an instance of class dynamically and invoke method?

Normally we create instance of class using new keyword followed by class name. In below example new instance of “TestClass” is created using new keyword.

TestClass test = new TestClass();

But if you want to create an instance of class dynamically from assembly, how you can do it? You can do it using reflection by calling Activator.CreateInstance method. Activator class is part of System namespace. See below example how Activator.CreateInstance method used to create an instance of type.

namespace TestLibrary
{
    public class TestFile
    {
        public void DisplayFileName(string fileName)
        {
            Console.WriteLine("File Name :- {0}", fileName);
        }
    }
}




"TestLibrary" class library project added to console application and created above mentioned "TestFile" class and added reference of "TestLibrary" project to console application.  See below code from console application to dynamically create an instance of "TestFile" class and invoke "DisplayFileName" method.

Code -
public class Program
{
    static void Main(string[] args)
    {
        //Loads Assembly
        Assembly assembly = Assembly.Load("TestLibrary");
        //Gets type which object you wants to create
        Type t = assembly.GetType("TestLibrary.TestFile");
        //creates an instance of given type
        object obj = Activator.CreateInstance(t);
        //parameters for method
        object[] parameters = new object[] {"Binary File"};
        //Invokes method of class
        t.InvokeMember("DisplayFileName", BindingFlags.InvokeMethod, null, obj, parameters);

        Console.ReadLine();
    }
}


Output - 









In above example, an instance of “TestFile” class (of different assembly) is created and invoked “DisplayFileName” method dynamically.

First you need to load “TestLibrary” assembly using Assembly.Load method. You need to add reference of “TestLibrary” assembly in your application. If you want to load other assembly which is not referenced in your project, then you can use Assembly.LoadFile method to load external assembly. After successfully loading assembly, you need to load class using Assembly.Gettype instance method and create instance of that class using Activator.CreateInstance method. Once you get an instance of “TestFile” class, you can invoke “DisplayFileName” method via type InvokeMemeber method. The whole process is done dynamically via Reflection.

After reading this article, I hope you have more understating about how you can create an instance of class and invoke method dynamically via reflection. Please leave your feedback in comments below.

References –

See Also –