Pages

Friday, September 30, 2011

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 Thread. Background 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.

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.

publicstaticvoid Main()

{

Console.WriteLine("Calling from Main Thread...");

Console.WriteLine("Is Thread Pool Thread : " +

Thread.CurrentThread.IsThreadPoolThread.ToString());

Task.Factory.StartNew(DoSomething);

}

privatestatic 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.

publicstaticvoid 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

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.

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.

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.

Wednesday, September 28, 2011

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 Winformsapplication 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.

publicstaticvoid Main()

{

try

{

Thread thread = newThread(newThreadStart(DisplayName));

thread.Start();

}

catch (DivideByZeroException ex) //Exception will not handled here

{

MessageBox.Show(ex.ToString());

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

}

publicvoid 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.

publicstaticvoid Main()

{

Thread thread = newThread(newThreadStart(DisplayName));

thread.Start();

}

publicvoid 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.

Tuesday, September 27, 2011

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.Managementnamespace 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.

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 =

newManagementObjectSearcher("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.

Monday, September 26, 2011

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.

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.