Friday, September 30, 2011

Working with Thread Pool in C# (Dotnet)


What is Thread Pool?

Thread pool is collection of Threads which can be used to perform different tasks in background. All threads available in Thread Pool can be used as Background ThreadBackground thread runs asynchronously in background and remains main thread active (UI will be responsive). When you create and start Thread it takes some significant time to create it in memory, instead Thread pool can be used. Thread pool manages overhead to create and recycle threads. Thread pool keeps watch on total number of worker threads are running asynchronously if it reached to its limit then threads are queued up and wait until any of the thread finishes its task from Thread pool. This way thread pool reuses the threads and avoids the cost of creating new threads each time. We can explicitly set Max and Min limit of Threads that Thread Pool creates by calling ThreadPool.SetMaxThread and ThreadPool.SetMinThread methods respectively.


How to work with Thread Pool?

There are number of ways to use thread pool in your application.

1.       ThreadPool.QueueUserWorkItem
2.       Task Parallel Library (PLINQ)
3.       Delegates (asynchronous delegates)
4.       BackgroundWorker


ThreadPool.QueueUserWorkItem

Thread pool class provides facility to queue items using QueueUserWorkItem method. This method accepts WaitCallBack delegate. Let’s have a look on below code.

public static void Main()
{
    Console.WriteLine("Calling from Main Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());

    ThreadPool.QueueUserWorkItem(DoSomething);
}

private static void DoSomething(object x)
{
    Console.WriteLine("Calling from Thread Pool's Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    Console.WriteLine("Hi, I am using Thread Pool");
}

Output
Calling from Main Thread...
Is Thread Pool Thread : False
Calling from Thread Pool's Thread...
Is Thread Pool Thread : True
Hi, I am using Thread Pool

In above code, I have used ThreadPool.QueueUserWorkItem method to request queue for my task from Thread pool. This methods queue thread requested and allocate thread from thread pool class if available. This method accepts WaitCallBack delegate and as per delegate signature it accepts one argument of object type so I have added one argument to DoSomething method. In above code I have not passed any argument to DoSomething method so it will take null as default. Another interesting thing is you can check whether the thread is from Thread pool or not using Thread.CurrentThread.IsThreadPoolThread. This property returns true if the thread is from Thread pool and returns false if not.


Task Parallel Library (PLINQ)

Task Parallel Library is introduced with Dotnet Framework 4.0. We can use Task class of TPL to enter into Thread Pool. Task class provides Factory to start new task from Thread pool. Let’s have a look on below code.

public static void Main()
{
    Console.WriteLine("Calling from Main Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());

    Task.Factory.StartNew(DoSomething);
}

private static void DoSomething()
{
    Console.WriteLine("Calling from Thread Pool's Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    Console.WriteLine("Hi, I am using Thread Pool");
}

Output
Calling from Main Thread...
Is Thread Pool Thread : False
Calling from Thread Pool's Thread...
Is Thread Pool Thread : True
Hi, I am using Thread Pool

In above code, Task class used to start new thread from Thread pool. Task.Factory.StartNew method used to start thread from thread pool. StartNew method accepts delegate action as parameter.


Asynchronous Delegate

Asynchronous delegate internally uses thread from Thread Pool class. You can pass arguments and return value from delegate method. Let’s have a look on below code.

public static void Main()
{
    Console.WriteLine("Calling from Main Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());

    Func<string, int> MyDelegate = DoSomething;
    MyDelegate.BeginInvoke("Hello", null, null);
}

private static int DoSomething(string x)
{
    Console.WriteLine("Calling from Thread Pool's Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    Console.WriteLine("Hi, I am using Thread Pool");
    return 0;
}

Output
Calling from Main Thread...
Is Thread Pool Thread : False
Calling from Thread Pool's Thread...
Is Thread Pool Thread : True
Hi, I am using Thread Pool

In above example, I made few changes in existing example and used asynchronous delegate. When you call BeginInvoke method of delegate it executes task in parallel thread and the thread will be pooled from ThreadPool class. I have created one Func<> delegate with string argument and integer as return type. This method is being executed in background thread of Thread pool class.


BackgroundWorker

Background worker class also uses thread from Thread pool to perform task in background. For more information about background worker you can go through my post on BackgroundWorker. Let’s have a look on below code
.
BackgroundWorker workerThread;

public static void Main()
{
    workerThread = new BackgroundWorker();
    workerThread.DoWork += new DoWorkEventHandler(workerThread_DoWork);
    workerThread.RunWorkerCompleted += new
        RunWorkerCompletedEventHandler(workerThread_RunWorkerCompleted);

    Console.WriteLine("Calling from Main Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    workerThread.RunWorkerAsync();  
}
private void workerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Console.WriteLine("Worker thread completed.");
}

private void workerThread_DoWork(object sender, DoWorkEventArgs e)
{
    Console.WriteLine("Calling from Thread Pool's Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    Console.WriteLine("Hi, I am using Thread Pool");
}

Output
Calling from Main Thread...
Is Thread Pool Thread : False
Calling from Thread Pool's Thread...
Is Thread Pool Thread : True
Hi, I am using Thread Pool
Worker thread completed.

As per above code, I have created one instance of BackgroundWorker class. I have also attached DoWork and RunWorkerCompleted methods to backgroundworker instance. So when I call RunWorkerAsync method of worker thread it will be executed on separate thread in background and thread will be pooled form Thread pool. When worker thread completes it will notify user with completed state.

As explained above, these all are the ways to use threads from Thread pool.

Hope you liked this post. Please leave your comments and feedback in comments section of this post.

See also –

How to install Windows8 Developer Preview in Virtualbox - Windows 8 first look


Microsoft has recently launched Windows 8 developer preview. You can find more information and videos about windows 8 here. I was excited to know what’s new in windows 8 so I have installed Windows 8 on Virtualbox and it's running well. So I would like to share my experience about Windows 8 and its  installation in this post.

Virtualbox is virtualization product and allows you to run multiple operating system at a time on your machine virtually. Virtualbox is freeware product available to home users. Please click on below links to know about virtualbox and download the same.


How to install Windows 8 in VirtualBox?


First download and install VirtualBox software and windows 8 developer preview from above mentioned link. Once VitualBox is installed you need to click on new button and follow the below screenshots to create new virtual machine.






After successful creation of virtual machine you can see Windows 8 Virtual machine is listed like in below image. Now you need to start that virtual machine by clicking on Start button. 






After that you have to select boot option (either DVD or USB) or need to provide ISO file to boot the virtual machine. I selected an iso file to boot my virtual machine. Once virtual machine is boot from ISO file you need to provide all the required information to install the windows 8 as an when asked.
 
  
In my case when I stated installation it was showing me some binary values as an error after first restart while installing windows 8. The reason was the Virtualization was disabled in my BIOS settings of my machine. So make sure that Virtualization is enabled from BIOS (if available).

Once your installation complete, you can see below first image of windows 8. I haven’t explored all the new features of windows8 as of now but will share in future when I complete exploring it. I would like to show you some images of windows 8 new features which I liked very much.








 


Hope you liked this post. Please leave your feedback and comments here.



Wednesday, September 28, 2011

How to handle exceptions while working with Threading?


Everybody knows how to handle exception in application using try catch and finally block. In this post I will explain how handle exception while working with Threading. Multiple threads can run inside single process parallelly. WPF and Winforms application runs on UI Thread and handled only exception which are thrown from the main thread. So when you create new Thread from application and the calling method throws an exception which is not handled by main UI Thread.

Let’s understand using simple example.

public static void Main()
{
    try
    {
        Thread thread = new Thread(new ThreadStart(DisplayName));
        thread.Start();
    }
    catch (DivideByZeroException ex) //Exception will not handled here
    {
        MessageBox.Show(ex.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}
public void DisplayName()
{
    int a = 0;
    int b = 10 / a; //throws unhandled exception
}

As per above code snippet, method DisplayName throws DivideByZeroException but it will not handled by the try catch block written inside Main() method and application shows unhandled application. Keep in mind that each thread has its own independent execution path. Let’s have a look on below code and see how to overcome with this scenario.

public static void Main()
{
    Thread thread = new Thread(new ThreadStart(DisplayName));
    thread.Start();
}

public void DisplayName()
{
    try
    {
        int a = 0;
        int b = 10 / a;
    }
    catch (DivideByZeroException ex)
    {
        MessageBox.Show(ex.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

In above code, exception is handled on DisplayName method and user can see the correct error message box showing exception information. So now exception is handled within or inside thread execution path and this is the effective way to handling exception with threading.

Hope you liked this tip and also know correct way to handle exception while working with threading.

See also - 

Tuesday, September 27, 2011

How to get System Information (Hardware and Software) in C# (WPF)?


Sometimes we need get some machine specific (hardware) information such as ProcessorID, Motherboard Name, Hard Disk Serial Number, Installed Printers, Installed Memory etc. We can get all these information using Dotnet. Dotnet provides System.Management namespace which is used to get all Hardware and Software information of your machine.

System.Management provides class called ManagementObjectSearcher which is used to query hardware and software information from machine based on key. We can get ManagementObjectCollection by calling get method of ManagementObjectSearcher class. Now get ManagementObject by iterating ManagementObjectCollection instance. ManagementObject class provides properties and using this property we can iterate all the PropertyData available under ManagementObject. 

Let’s have a look on below example created with C# and WPF.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0.7*" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="35"/>
        <RowDefinition />
    </Grid.RowDefinitions>
    <Label Content="Select Hardware:"
        VerticalAlignment="Center"
        Margin="5"
        Grid.Row="0" Grid.Column="0"/>
    <ComboBox Name="SysInfoComboBox"
        Grid.Row="0" Grid.Column="1"
        Margin="5"
        SelectionChanged="SysInfoComboBox_SelectionChanged"/>
    <ListBox Name="SystemInfoListBox"
        Grid.Row="1" Grid.ColumnSpan="2" Margin="5"
        ScrollViewer.HorizontalScrollBarVisibility="Auto"
        ScrollViewer.VerticalScrollBarVisibility="Auto"/>
</Grid>

void SystemInfo_Loaded(object sender, RoutedEventArgs e)
{
    FillComboBox();
}
void FillComboBox()
{
    SysInfoComboBox.Items.Add("Select a Value");
    SysInfoComboBox.Items.Add("OperatingSystem");
    SysInfoComboBox.Items.Add("DiskDrive");
    SysInfoComboBox.Items.Add("MotherboardDevice");
    SysInfoComboBox.Items.Add("Processor");
    SysInfoComboBox.Items.Add("Printer");
    SysInfoComboBox.Items.Add("ComputerSystem");

    SysInfoComboBox.SelectedIndex = 0;
}
void FillListBox(string value)
{
    List<string> items = new List<string>();
    ManagementObjectSearcher mSearchObj =
         new ManagementObjectSearcher("SELECT * FROM " + value);
    ManagementObjectCollection objCollection = mSearchObj.Get();

    foreach (ManagementObject mObject in objCollection)
    {
        foreach (PropertyData property in mObject.Properties)
        {
            items.Add(string.Format("{0}:- {1}", property.Name, property.Value));
        }
    }
    SystemInfoListBox.ItemsSource = items;
}
private void SysInfoComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (SysInfoComboBox.SelectedIndex > 0)
    {
        SystemInfoListBox.ClearValue(ListBox.ItemsSourceProperty);
        FillListBox("Win32_" + SysInfoComboBox.SelectedItem.ToString());
    }
}






In above example, I have added ComboBox and ListBox. ComboBox contains the key name of hardware of which we need to get information. Based on the value selected in Combobox the Listbox will get populated with information on selection changed event of combobox.

ManagementObjectSearcher mSearchObj =
         new ManagementObjectSearcher("SELECT * FROM " + value);
ManagementObjectCollection objCollection = mSearchObj.Get();

As per above code snippet, mSearchObj.Get() method will get ManagementObjectCollection based on passed value to query.

    foreach (ManagementObject mObject in objCollection)
    {
        foreach (PropertyData property in mObject.Properties)
        {
            items.Add(string.Format("{0}:- {1}", property.Name, property.Value));
        }
    }

The above nested foreach loop will iterate each ManagementObject available in objcollection and each PropertyData available in ManagementObject’s Properties. Inside nested loop I am adding Property Name and value into List collection of string and assigning to Listbox’s datasource.

Hope you liked this post. Please leave your comments and feedback in comments section of this post.

See also - 

Monday, September 26, 2011

How to get Visual Tree using VisualTreeHelper class in WPF?


You might be aware about Visual Tree and Logical Tree in WPF. If you are new to WPF and don’t know about visual tree and logical tree please go through my post on Visual Tree vs. Logical Tree first.

In this post I will demonstrate how to get Visual Tree using VisualTreeHelper class. VisualTreeHelper class is very useful class to navigate through element’s children. It provides some methods to get child element, to get parent element, total children etc. First let’s have a look on below code snippet.

<Window.Resources>
    <Style TargetType="TreeViewItem">
        <Setter Property="IsExpanded" Value="True" />
    </Style>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="0.2*" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <TreeView Name="treeView" VerticalAlignment="Top"
                Grid.Row="1" HorizontalAlignment="Left"
                ScrollViewer.HorizontalScrollBarVisibility="Auto"
                ScrollViewer.VerticalScrollBarVisibility="Auto"
                Height="Auto" Width="Auto"/>
    <Button Name="getVisualTree" Content="Get Visual Tree"
            Height="35" Width="150"
            Click="getVisualTree_Click"/>
</Grid>

private void getVisualTree_Click(object sender, RoutedEventArgs e)
{
    treeView.Items.Clear();
    AddElementToTree(this, null);
}

public void AddElementToTree(DependencyObject parent, TreeViewItem treeViewItem)
{

    TreeViewItem newTreeViewItem = new TreeViewItem();

    newTreeViewItem.Header = parent.GetType().ToString();

    if (treeViewItem == null)
    {
        treeView.Items.Add(newTreeViewItem);
    }
    else
    {
        treeViewItem.Items.Add(newTreeViewItem);
    }

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var childElement = VisualTreeHelper.GetChild(parent, i);
        AddElementToTree(childElement, newTreeViewItem);
    }
}



In above example, I have added one treeview control to XAML and set its TreeViewItem’s style to Expanded by default. I also added one Button named getVisualTree and its onclick event i am adding elements to treeview control.

AddElementToTree(this, null);

This method will retrieve visual tree of given dependency object. In our example i have provided ‘this’ as parent element. This will retrieve visual tree of Window. You can specify other elements if you want to retrieve specific element’s visual tree.

public void AddElementToTree(DependencyObject parent, TreeViewItem treeViewItem)
{

    TreeViewItem newTreeViewItem = new TreeViewItem();

    newTreeViewItem.Header = parent.GetType().ToString();

    if (treeViewItem == null)
    {
        treeView.Items.Add(newTreeViewItem);
    }
    else
    {
        treeViewItem.Items.Add(newTreeViewItem);
    }

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var childElement = VisualTreeHelper.GetChild(parent, i);
        AddElementToTree(childElement, newTreeViewItem);
    }
}

This method takes two arguments first one is dependency object and another is treeview item. This method uses help of VisualTreeHelper class to get child.

VisualTreeHelper.GetChildrenCount(parent)

Above method returns total number of children of parent element. Below method return child element of parent at specified number.

VisualTreeHelper.GetChild(parent, i)

So the above for loop will get all the children of an element. This method is called recursively until all elements are added to the tree.


See also –