Showing posts with label Process. Show all posts
Showing posts with label Process. 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 –

Thursday, January 12, 2012

Performance Counters in .Net


Introduction

Performance counters allow us to monitor physical devices such as Processor, Memory, CLR, Network, Threads etc. Windows provides performance monitor utility to view performance counters. To open that utility need to go to Start -> Run and type “perfmon” and press enter. Below is the screenshot of Performance Monitor utility.



This application monitors various system components, as per above image it displays the processor time utilization. There are multiple performance counters available to monitor different devices. Those performance counters are grouped under categories. Below screenshot displays Add Counter window of performance monitor utility.



Above image displays various categories like Processor, Process, Print Queue, Power Meter etc. Each category has its own counters, as per above image Processor category has “% C1 Time”, “% C2 Time” and so on. Category may have instances and if it has then it will be displayed in instance list. Instance list of selected category is available below the category list. 

Enumerating available categories

Dotnet provides PerformanceCounterCategory class to get all the categories of performance counters. This class is available in System.Diagnostics namespace. GetCategories methods returns collection of PerformanceCounterCategory. Let’s have a look on below code.

//Get all performance categories
PerformanceCounterCategory[] perfCats = PerformanceCounterCategory.GetCategories();
foreach (PerformanceCounterCategory category in perfCats.OrderBy(c => c.CategoryName))
{
    Console.WriteLine("Category Name: {0}", category.CategoryName);
}

Output –

Category Name: .NET CLR Data
Category Name: .NET CLR Exceptions
Category Name: .NET CLR Interop
Category Name: .NET CLR Jit
Category Name: Active Server Pages
Category Name: APP_POOL_WAS
Category Name: ASP.NET
Category Name: Per Processor Network Interface Card Activity
Category Name: PhysicalDisk
Category Name: Print Queue
Category Name: Process
Category Name: Processor



The above code displays all available performance counter categories order by category name.

Performance Counters by Category

Below example demonstrates how we can get all the performance counters for given category. We can also get all the counters for all the categories if you don’t specify category name in below code but it will take a while to execute. So in below code I have retrieved performance counters only for "Memory" category.

//Get all performance categories
PerformanceCounterCategory[] perfCats = PerformanceCounterCategory.GetCategories();

//Get single category by category name.
PerformanceCounterCategory cat = perfCats.Where(c => c.CategoryName == "Memory").FirstOrDefault();
Console.WriteLine("Category Name: {0}", cat.CategoryName);

//Get all instances available for category
string[] instances = cat.GetInstanceNames();
if (instances.Length == 0)
{
    //This block will execute when category has no instance.
    //loop all the counters available withing category
    foreach (PerformanceCounter counter in cat.GetCounters())
        Console.WriteLine("     Counter Name: {0}", counter.CounterName);
}
else
{
    //This block will execute when category has one or more instances.
    foreach (string instance in instances)
    {
        Console.WriteLine("  Instance Name: {0}", instance);
        if (cat.InstanceExists(instance))
            //loop all the counters available withing category
            foreach (PerformanceCounter counter in cat.GetCounters(instance))
                Console.WriteLine("     Counter Name: {0}", counter.CounterName);
    }
}

Output –

Category Name: Memory
     Counter Name: Page Faults/sec
     Counter Name: Available Bytes
     Counter Name: Committed Bytes
     Counter Name: Commit Limit
     Counter Name: Write Copies/sec
     Counter Name: Transition Faults/sec
     Counter Name: Cache Faults/sec
     Counter Name: Demand Zero Faults/sec
     Counter Name: Pages/sec
     Counter Name: Pages Input/sec
     Counter Name: Page Reads/sec
     Counter Name: Pages Output/sec
     Counter Name: Pool Paged Bytes
     Counter Name: Pool Nonpaged Bytes
     Counter Name: Page Writes/sec
     Counter Name: Pool Paged Allocs
     Counter Name: Pool Nonpaged Allocs
     Counter Name: Free System Page Table Entries
     Counter Name: Cache Bytes
… … …

The above code returns name of the counters available in 'Memory' category. Memory category doesn’t contain any instances so it will list all the performance counters without displaying instance name. We can also execute same code for category which has instances. So let’s execute the same code with “Processor” category.

PerformanceCounterCategory cat = perfCats.Where(c => c.CategoryName == "Processor").FirstOrDefault();

Output –

Category Name: Processor
  Instance Name: _Total
     Counter Name: % Processor Time
     Counter Name: % User Time
     Counter Name: % Privileged Time
     Counter Name: Interrupts/sec
     Counter Name: % DPC Time
     Counter Name: % Interrupt Time
     Counter Name: DPCs Queued/sec
     Counter Name: DPC Rate
     Counter Name: % Idle Time
     Counter Name: % C1 Time
     Counter Name: % C2 Time
     Counter Name: % C3 Time
     Counter Name: C1 Transitions/sec
     Counter Name: C2 Transitions/sec
     Counter Name: C3 Transitions/sec
  Instance Name: 0
     Counter Name: % Processor Time
     Counter Name: % User Time
     Counter Name: % Privileged Time
     … … …
  Instance Name: 1
     Counter Name: % Processor Time
     Counter Name: % User Time
     Counter Name: % Privileged Time
     … … …

As per change in category of above code, now output displays all the performance counters available in 'Processor' category. Processor category has three instances so it will list all the performance counters with instance name.

Reading Performance Counter Value

PerformanceCounter class used to retrieve value of performance counter. This class is also available in System.Diagnostics namespace. We need to pass CategoryName, CounterName and InstanceName (Optional) to PerformanceCounter class constructor or we need to set those properties to performance counter instance explicitly. Performance counter instance has NextValue method which can be used to retrieve the value of give performance counter. 

Let’s have a look on below code.

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0,0,1);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();

void timer_Tick(object sender, EventArgs e)
{
    using (PerformanceCounter perfCounter = new PerformanceCounter("Memory",
             "Available MBytes"))
    {
        float value = perfCounter.NextValue();
        Console.WriteLine("Total Memory Available: {0} MB.", value);
    }
}

Output –

Total Memory Available: 236 MB.
Total Memory Available: 239 MB.
Total Memory Available: 236 MB.
Total Memory Available: 231 MB.
Total Memory Available: 218 MB.
Total Memory Available: 221 MB.
Total Memory Available: 237 MB.
Total Memory Available: 237 MB.



Adding custom categories and counters

The new counters and categories can be added and measured through C# code. Dotnet provides PerformanceCounterCategory class to create new category and CounterCreationData class to create new performance counter.  You can create multiple counters under single category. The create method of PerformanceCounterCategory accepts collection of CounterCreationData. Let’s have a look on below code.

string category = "MyCategory";
string counter1 = "Counter1";
//Check whether category is exist or not
if (!PerformanceCounterCategory.Exists(category))
{
    //creates collection of CounterCreationData
    CounterCreationDataCollection counterDataCollection =
           new CounterCreationDataCollection();

    //added new CounterCreationData to counterDataCollection
    counterDataCollection.Add(new CounterCreationData(counter1,
          "My custom counter", PerformanceCounterType.NumberOfItems32));

    //Creates new category based on information and creates
      counters available in counter data collection
    PerformanceCounterCategory.Create(category, "My Category", PerformanceCounterCategoryType.SingleInstance, counterDataCollection);
}

Output –

As per above image from performance monitor tool, MyCategory is created and Counter1 is added to it. You can delete category by calling PerformanceCounterCategory.Delete method. To create and delete performance counters and categories you need administrative privileges



See Also –

Monday, January 2, 2012

How to get list of running processes in C#?



Process class provides GetProcess method to get all running processes. The GetProcesses method returns collection of process. Similarly GetCurrentProcess method returns currently running processProcess class is available in System.Diagnostics namespace. 


Let’s have a look on below code.

void ProcessThreads_Loaded(object sender, RoutedEventArgs e)
{
    foreach (Process p in Process.GetProcesses())
        Console.WriteLine("{0} | {1} | {2}", p.ProcessName, p.Id, p.Threads.Count);


    Console.WriteLine("Current Process");

    Process current = Process.GetCurrentProcess();
    Console.WriteLine("{0} | {1} | {2}", current.ProcessName, 
                       current.Id, current.Threads.Count);
}

Output


svchost | 616 | 13
SearchIndexer | 3344 | 14
lsm | 584 | 12
spoolsv | 1764 | 13
COH32 | 5112 | 3
WPFTestApplication.vshost | 2660 | 14
lsass | 576 | 9
RegSrvc | 2348 | 4
COH32 | 4908 | 1
SNAC | 1360 | 13
services | 568 | 6
explorer | 5884 | 26
svchost | 956 | 19
iexplore | 756 | 16
ccSvcHst | 1540 | 36
svchost | 3704 | 5
rundll32 | 3868 | 2

Current Process
WPFTestApplication.vshost | 2660 | 14

The above output displays all the processes with its name, id and total thread count. The last line displays currently running process.

Displaying Process Threads


We can get list of all the threads running under process using Threads collection of Process instance. Let’s have a look on below code.

void ProcessThreads_Loaded(object sender, RoutedEventArgs e)
{
    foreach (Process p in Process.GetProcesses())
    {
        Console.WriteLine("{0} | {1} | {2}", p.ProcessName, p.Id, p.Threads.Count);
        DisplayThreads(p);
    }
}

private void DisplayThreads(Process p)
{
    foreach (ProcessThread thread in p.Threads)
    {
        Console.WriteLine("          {0} | {1} | {2} | {3}", thread.Id,
            thread.PriorityLevel, thread.ThreadState, thread.TotalProcessorTime);
    }
}

Output

wininit | 468 | 3
          472 | Highest | Wait | 00:00:00.4992032
          556 | Normal | Wait | 00:00:00
          564 | Normal | Wait | 00:00:00
LMS | 1252 | 8
          1304 | Normal | Wait | 00:00:00.0468003
          1336 | Normal | Wait | 00:00:00
          1924 | Normal | Wait | 00:00:00.2496016
          2072 | Normal | Wait | 00:00:00.0624004
          2180 | Normal | Wait | 00:00:08.6424554
          1692 | Normal | Wait | 00:00:00
          5552 | Normal | Wait | 00:00:00
          3700 | Normal | Wait | 00:00:00


Above code displays list of processes along with their ProcessThreads.


See Also – 
How to create custom Application Domain?
How to get system hardware information?
How to pass data as an argument to Thread?

Tuesday, December 13, 2011

How to create custom Application Domain?



Each .NET application by default creates one application domain. The default application domain created by CLR automatically when process (application) starts. Application domain is the runtime unit of isolation in which runs .net application in managed memory boundary. Application domain created under process and process can have one or more application domains. See below figures.

Process with single Application Domain


 Process with multiple Application Domains



Creating Custom Application Domains

AppDomain class is provided by .Net to create custom application domain. AppDomain.CreateDomain and AppDomain.Unload methods are provided to create and destroy custom application domain. Let’s have a look on below code.

public class MyClass
{
       public static void Main()
       {
              AppDomain appDomain = AppDomain.CreateDomain("My Domain");
appDomain.DoCallBack(new CrossAppDomainDelegate(HelloMethod));
Console.ReadLine();
AppDomain.Unload(appDomain);
       }
       public static void HelloMethod()
       {
              Console.WriteLine("Hello from " + AppDomain.CurrentDomain.FriendlyName);
       }     
}



In above example, AppDomain.CreateDomain method creates new application domain named “My Domain” and AppDomain.Unload method unloads or removes "My Domain". DoCallBack method is used to execute action on another application domain. The HelloMethod is static so DoCallBack (CrossAppDomainDelegate) delegate is referencing a static method.

AppDomain also provides ExecuteAaasembly method which will execute an assembly file.

AppDomain appDomain = AppDomain.CreateDomain("My Domain");
appDomain.ExecuteAssembly("WPFApplication1.exe");
Console.ReadLine();
AppDomain.Unload(appDomain);

When you create a new application domain within your current process, CLR keeps isolated one application domain from other. So each application domain has its own separate memory and objects which can’t clash with other application domain.

Sharing Data between application domains

We can share data between application domains using named slots. AppDomain instance provides SetData method to set data as name and data pair. While the GetData method retrieves an object (data) based on given name. Below are the signatures of both the methods. 

public void SetData(string name, object data);
public object GetData(string name);

Let’s have a look on below code.

public class MyClass
{
       public static void Main()
       {
              AppDomain appDomain = AppDomain.CreateDomain("My Domain");
appDomain.SetData("AppDomainOwner", "Mitesh Sureja");
appDomain.DoCallBack(new CrossAppDomainDelegate(HelloMethod));
Console.ReadLine();
AppDomain.Unload(appDomain);
       }
       public static void HelloMethod()
       {
              Console.WriteLine("Hello from " + AppDomain.CurrentDomain.FriendlyName);
       Console.WriteLine("Created By " + AppDomain.CurrentDomain.GetData("AppDomainOwner"));
       }     
}


As shown in above example, SetData method set name as “AppDomainOwner” and data as “Mitesh Sureja”. While GetData method retrieves data as an object based on given name.

Another way to share data between multiple application domains is using Remoting.

Hope you liked this post related to application domain. Please feel free to write your comments/feedback in comments section below.

See Also -