Wednesday, April 17, 2013

Threads in C# .Net use of locks etc

Hello Friends,
I am back with a new post related to threads again.But this time i am going to explain them in a very simple manner for the perspective of a new bee in coding :) 
Lets start without talking too much.Well we all know that whatever we write in our program runs in a MAIN THREAD which actually is nothing but acts like the father of all its children threads.
Main function :

  static void Main(string[] args)
        { 
            //Everything written here will run in the main thread.
        }

Creation of thread :
We use namespace System.Threading as it contains all the necessary classes & ,methods which are used for threads.


  static void Main(string[] args)
        {
            //creating thread
            ThreadStart thStrt = new ThreadStart(WriteOnScreen);
            Thread thread1 = new Thread(thStrt);
            thread1.Start();
      }

 public static void WriteOnScreen()
        {
            Console.WriteLine("Hello i am from thread.");
        }


You must have to notice 2 points in above code snippet -
1. We need Thread Start object to pass in thread.
2. Thread Start object contains Method name. Method must be STATIC which we are passing in it.

Calling Method with parameters in thread :
We have 2 popular ways to do this-
  • Using delegate object. - 
 public static void WriteThisOnScreen(object toWrite)
        {
            Console.WriteLine("Hello i am from parameterized thread. "+toWrite);
        }

 static void Main(string[] args)
        {
            //creating thread with parameters
            ThreadStart threadStrt = delegate{ WriteThisOnScreen("Pragya"); };
            Thread thread2 = new Thread(threadStrt);
            thread2.Start();

        }

  • Using Parameterized Thread object.
 static void Main(string[] args)
        {
            //parameterized thread
            ParameterizedThreadStart paramThS = delegate(object o) {   WriteThisOnScreen("Pragya"); };
            paramThS.Invoke("Pragya");
        }


Understanding Synchronization :Use of lock -


Suppose there is a function like this:

 public static void PerformOperation(int a, int b)
        {
            int resultOfDivision = a / b;
            Console.WriteLine("Result of division is " + resultOfDivision);
            a= 0;
            b= 0;

        }
 static void Main(string[] args)
        {
           
            ThreadStart threadStrt3 = delegate { PerformOperation(10,20); };   
            Thread thread3 = new Thread(threadStrt3);
          

            ThreadStart threadStrt4 = delegate { PerformOperation(10,20); };   
            Thread thread4 = new Thread(threadStrt4);

            thread3.Start();
            thread4.Start();
        }

Now if i will call this method using two different threads then it will lead an exception :
DivideByZero Exception.
Do u know why??? Because when thread 3 was making b=0 at that time thread 4 was doing a/b which gives divide by 0 exception.
So in such cases where you need to control that at a time only one thread would access a variable or certain piece of code we use mutual exclusion mutex lock using keyword lock.

Now problem would be resolved by using this :

 public static void PerformOperation(int a, int b)
        {
            lock(this)
          {

            // At a time only one thread will enter in this code region.....
            int resultOfDivision = a / b;
            Console.WriteLine("Result of division is " + resultOfDivision);
            a= 0;
            b= 0;
          }

        }

Very simple solution :)

Lets talk about a problem which is caused due to wrong use of locks.
We all must have heard about it.It is DEADLOCK..
ummm no point is How a developer can ruin his/her code by using locks in wrong way?
answer is : See this example

    public static void MyMethod()
   {
        lock(a)
        {
              // some piece of code...
            lock(b)
           {
               // some piece of code...
           }
       }
  }

    public static void SomeOtherMethod()
   {
        lock(b)
        {
              // some piece of code...
            lock(a)
           {
               // some piece of code...
           }
       }
  }


Suppose thread 1 is running MyMethod() and locking a & processing while at the same time thread 2 is running in SomeOtherMethod() and locking b & processing. So are you getting the problem???? yep you are right. when thread 1 will go to line where lock(b) is required it will wait until it get the lock for b & at the same time when thread 2 will come to the line where lock(a) is required it will also wait until get lock for a. where lock of b is acquired by thread 2 & lock of a is acquired by thread 1 both threads will make DEADLOCK.

so the point of advice is :)
do not use too muck locks without thinking.

Well Thanks for reading this.hope it was needful.
Soon i will publish new and interesting small articles.

Thanks.
Pragya Sharma
Software Engineer
INDIA

Wednesday, September 19, 2012

Multithreading in WPF (Windows Presentation Foundation) PART : 1

Hello Friends,

In my this post i will explain Multithreading from very beginning. As we all must have heard the term 'Thread'. We know that whenever we want to do parallel processing we uses threads.
So lets start from the basic building block needed to understand implementation of multithreading in WPF application.Once we know the basic logic behind Parallel programming it can be used in any kind of application.Here i will use C# language to give examples or sample codes.

Suppose we have an application that have many modules in it . It may include long running tasks,few tasks which needs user interactions or anything else. If we want to implement threading then we must know that which weapon we will use to hit the problem in the best way. :)

Few of the weapons for you guys are ---

  •  Background Worker
  • Thread
  • Thread pool
  • I will also explain about Dispatcher timer because wherever we need to run certain piece of code after an interval then we uses timers. In WPF we uses Dispatcher timer.
Lets begin in detail one by one,

Background worker :

We uses background worker where we need to seperate a task from our main running thread.
 Let me explain it in more simple words.....Suppose we have an application in which we want to run a task in background and just want to make it complete without any disturbance then we can put that piece of code in background worker's DoWork eventhandler.
Before using this we must know few very basic and very important points about it and they are -
                  BackgroundWorker mybgworker = new BackgroundWorker();
  • How to use its properties & mots important its events :-
                    mybgworker.WorkerSupportsCancellation = true;
                   mybgworker.WorkerReportsProgress = true;
-----//DoWork : this is the most important eventhandler all the tasks you want to do in background worker must be written in this.
          mybgworker.DoWork += new DoWorkEventHandler(mybgworker_DoWork);
mybgworker.ProgressChanged += new ProgressChangedEventHandler(mybgworker_ProgressChanged);
mybgworker.RunWorkerCompleted +=  new RunWorkerCompletedEventHandler(mybgworker_RunWorkerCompleted);

----If you wants to have access to cancel background worker processing at any moment from your code then you must need to enable this property as true. ( For ex: On a Cancel buton's Click you want to cancel background worker)

private void mybgworker_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    for (int k = 1; (k <= 10); k++)
    {
        if ((worker.CancellationPending == true))
        {
            e.Cancel = true;
            break;
        }
        else
        {
          
            System.Threading.Thread.Sleep(500);
            worker.ReportProgress((k * 10));
        }
    }
}

--- If you wants to keep on checking progress of your background worker then you can set reports progress property true.(For ex: you want to run your progress bar in background then you can check at any state of processing.)
private void mybgworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    this.txtProgress.Text = (e.ProgressPercentage.ToString() + "%");
}
-----Runworkercompleted is used if you want to do something at the timewhene worker has been finished its work.
 private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
//----write your code here friends....
 } 
Everything is useless if your wont start running this worker by writing 
           mybgworker.RunWorkerAsync();
  • Now comes the logical part -----
IF YOU KNOW THE LOGIC YOU CAN IMPLEMENT THREADING IN ANY APPLICATION
 -------------------------------------------------------------->>
*  If one thread is running and doing certain tasks and during its processing it is accessing certain objects, UI elements then any other thread can not access it.This is the basic and main logic in the processing of thread.It is also called thread affinity.
*If you are using multithreading in your code and you want to access any object or UI element which might be also been accessed by some other thread parallel or not.You have to use Dispatcher to access it else you will get following exception :
    The calling thread cannot access this object because a different thread owns it.

this.Dispatcher.Invoke(
            new Action(() =>
            { //write your code here friends...... }));

* Before adding any method in Thread Remember to make its state ( Apartment state )  as STA like this.
     Thread th =  new Thread(Write your methodname here );
       th.SetApartmentState(ApartmentState.MTA);
If you will not add this line then you will get this exception :
   The calling thread must be STA, because many UI components require this.

*  In WPF if you are using multi threading then NEVER access your controls without dispatcher else you will definitely get exceptions
------------------------------------------------------------<<
  • Lets come back to our backgroundworker part,so in actual background worker itselef runs in a seperate thread so if you are trying to access any object/UI component in its DoWork then you must have to use dispatchers.
  • You can use any control any method anything without dispatcher in RunWorkerCompleted as at time thread of backgroundworker has been ended.
By taking care of only these few little but most important fundas to implement threads.
This was the PART One explaining basic concepts to implement threading using background worker.I will explain Thread and threadpool in my next parts of this post.
Thanks & Regards,
Pragya Sharma
Software Engineer
INDIA



Monday, September 17, 2012

Developing Windows Applications ( Using Windows Forms vs WPF) in .Net Framework


Hello Friends,

In this article I am going to explain the two very important 
technologies which are being used in developing various kind of 
windows applications.Before starting let me allow to introduce that what is Windows applications...If you are new in development then you must have an idea of web applications yes for sure .net is very beneficial in developing Web applications.
The main advantage of using the .Net technology is the reduced amount of code necessary for building applications. Better performance is provided by using the just-in-time compilation, early binding, caching services and native optimization.The .Net technology is language independent, which lets users choose the language that will suit best for their applications.There are many languages provided by .net framework which can be used by developer.some of them are c#,ASP.net, PHP ,VB , j# etc.But except web applications .Net plays a very special role in 
windows application development.In simple words windows applications means any application that is not a web application is commonly a windows application.Only creation of windows forms , user controls does not comes in windows applications.We can create various add ins for outlook ( i will explain in future posts) internet explorer and other browsers,  Remoting environment applications for communications between systems 
using ports , Messangers , Media players , video players  and many more.trust me its a very wide domain.
Lets start with a very basic point which often confuses us that for which purpose we should use windows form application or to use WPF application.
WPF windows presentation foundation is a new technology presented by .net framework.It gives a lot of extra features to enhance the 
quality of a windows application.Not only in GUI but also in its 
expendability . At this point I recommend doing all new development in WPF because the experience is that much better.But for starting in development it is recommended to use windows form application development first.
Yes, WPF is a brilliant technology and it has benefits that span far beyond mere eye-candy.... the templating and binding capabilities are great examples. The whole object model offers more flexibility and broader possibilities. That doesn't, however, make it the defacto platform for future LOB applications.
The "Problems" which WPF solves in terms of separating GUI from 
business logic aren't problems which can't be readily solved in 
Windows Forms by simply starting with the right architecture and 
mind-set. Even the object-path binding capabilities of WPF can be 
reproduced in Windows Forms with some very simple helper classes. 
Windows forms can be used where GUI is not a big concern but WPF is useful in both cases.
WPF is not intended to replace Windows Forms.I used to think it was intended to be a replacement for WinForms, but it is not.  WinForms is still alive and well, and will continue to be enhanced and supported by Microsoft for years to come.  WPF is simply another tool for Windows desktop application developers to use, when appropriate.


Benefits of Windows Forms:

-Window Forms is a mature "forms over data" technology. It has an 
extensive ecosystem of controls, developers, and vendors that has 
evolved over the last twenty years of development .
-There are also some features that are unique to this platform. 
Windows Forms has a wide range of controls for presenting tabular 
data, for working with system dialogs, for graphics metafiles, and for date, time and calendar support. 
-Microsoft has announced the continued support of Windows Forms so if you have an existing Windows Forms application you can feel secure in a good level of support for your existing code base. 
-Windows Forms is the possibility of using the same API, regardless of the programming language that .NET software developers have chosen to write a Windows Forms application. Earlier the choice of programming language impacted the choice of API. Now all Windows Forms applications use one API from the .Net framework library. The knowledge of one API is enough to allow software developers to write Windows Forms applications in any language they will choose.
-Various Windows Forms control elements emulate the features of high quality applications, such as Microsoft Office. Using such control elements of Windows Forms as ToolStrip and MenuStrip, a .NET software developer can create toolbars and menus containing text and images, browse sub-menus and place other control elements such as inscriptions and drop-down lists.
-WPF will not run on windows 2000 or lower.


Benefits of Windows Presentation Foundation:


-Windows Presentation Foundation was created to allow developers to easily build the types of rich applications that were difficult or impossible to build in Windows Forms, the type that required a range of other technologies which were often hard to integrate. For example, the medical application below combines 2D & 3D graphics with re-styled forms element and interactive visualizations allowing the user to better understand and evaluate their data
-WPF is the platform of choice for today’s visually demanding 
applications with its inherent support of rich media, data 
visualization, complex text content, dynamic interactive experiences, and branded or custom look and feel.
-If you’re wanting to create a new experience for your users that is rich, interactive, sophisticated, or highly custom or branded, WPF is Microsoft’s next-generation platform for your project today.
-DataBinding in Wpf is better than windows forms.
- WPF provides a fast GUI experience to user due to its design and xaml desgin files.

At the end of this initial post.

* If you want to learn new technology to create rich GUI applications 

then WPF is waiting for you :) 
* If you want to hold your current technology and want to enhance in 

itself then enjoy working in WinForms. but whenever in future 
applications will need 3D animations in your form or a better GUI 
including various controls you will definitely create a project using WPF.For those applications where GUI and user interfaces are minimal like add ins , Remoting applications, background worker dedicated applications then go for windows form without any doubts....
All the best...
I Will post about Windows forms applications in my next post.In that post i will also define those little obstacles which becomes the headache of a programmer while developing an app in windows 
environment. ;) 

Regards,

- Pragya Sharma
Software Engineer
INDIA

Friday, September 14, 2012

Introductory Post

Hello Friends,

This is Pragya here to share my own experiences regarding learning.....Before blogging some useful information for you,allow me introduce myself......I am a Software engineer working on .Net Framework technology.I spent my 8 hours daily in coding.I Love to code...My aim is to share my experiences my own views my own way of exploring and expressing Education in this blog through my various posts.......I will blog in following areas... 

1.  Developing various applications using .Net
2.  Database 
3.  Tricks and Tips Useful for an efficient coder.
4.  Design and analysis of Algorithms 
5.  Computer Networks
6.  C ( Get Ready swimmers to swim in C ;) )
7.  Unix 
8.  Automata 
9.  Compiler
10. Innovative ideas yet to implement


I will try to discuss those points on which no one has discussed like this before.It would be very good experience for me to share my knowledge and wish that it would be beneficial for all of you.

Thanks & Regards,

- Pragya Sharma
Software Engineer 
Owner of easetolearn ( A group of aspiring leaders to make education easier than ever )
Email Address : easetolearn@gmail.com
INDIA