Following are the links for the examples to implement threads :
1.Simple implementation of threads
2.Complex implementation of threads example
3.Retrieving data from threads
4.Passing data to threads
Free Online Training VIDEOS,SAMPLES,TUTORIALS ON MCTS EXAM C#.NET(MS VISUAL STUDIO) Thanks for your support. The blog is getting bigger and better day by day. please check out : www.blog.sameershaik.com for further interesting articles on other microsoft certification examinations
Search this blog
You can search for all the topics in our blog using our google custom search now.
Search the blog
Loading
Showing posts with label Topic Threading. Show all posts
Showing posts with label Topic Threading. Show all posts
Wednesday, January 5, 2011
Sunday, June 20, 2010
Retrieving data from threads C# example
To understand how to retrieve data from threads, you need to have complete understanding of how delegates work. If you are unsure about how delegates works, you can check out my previous post on delegates on the link below:
Delegates tutorial
The above post provides you video tutorial on the same topic, so do check it out.
Step-1:
Now, to retrieve data from a thread, you need to create a method that accepts return results as a parameter and to that we need to create a delegate for the method.
For example, Imagine a thread is passing salary of an employee to a method called displaySalary. The method definition of displaySalary is as follows:
public static void displaySalary(int salary)
{
Console.WriteLine("Renewed salary of the employee is : "+salary );
Console.WriteLine("Press any key to clear the screen: ");
Console.ReadKey();
Console.Clear();
flag = 0;
}
As i said, to the above method a thread is going to pass value "salary". But for a thread to pass value to this method, we need to create a delegate for the above method.
This is how you create a delegate with exact same signature as the method displaySalary.
public delegate void Mydelegate(int value);
Remember the above statement doesn't link your delegate to the specified method. To link your method to delegate, you must create an obect of the delegate as follows:
Mydelegate PassValDelegate = new Mydelegate(displaySalary);
Great, now you have a delegate object linking to your method. Now for the next step of passing value from a thread.
Step-2:
Imagine i have a method called setSalary, whose definition is as follows:
public void setSalary()
{
Console.Clear();
Console.WriteLine("Please provide the hike in salary and press enter:");
int hike = Convert.ToInt32(Console.ReadLine().ToString());
int Reviewedsalary = Convert.ToInt32(salary) + hike;
}
Create a thread to execute above method in background as follows:
Thread t1 = new Thread(new ThreadStart(setSalary));
t1.Start();
If i want to pass Reviewedsalary value to the method displaySalary, then i need to pass it using the delegate object created above. So now our method setSalary would look like this:
public void setSalary()
{
Console.Clear();
Console.WriteLine("Please provide the hike in salary and press enter:");
int hike = Convert.ToInt32(Console.ReadLine().ToString());
int Reviewedsalary = Convert.ToInt32(salary) + hike;
//you can pass value to displaySalary using the delegate object as follows
PassValDelegate(Reviewedsalary);
}
This is little complex to understand.However check out my video, i will try to explain few things which can't be explained in writing.
Now for the working example of the above tutorial. Please check out the delegates examples by following the link i have provided you in the beginning of the post so that understanding this example will be easier.
Please start a console project and name it as PassValBetThreads. To this project add a class and name it as employee. My class employee has 4 methods which display information about employee and 2 methods which set employee information. Go ahead and write the methods as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PassValBetThreads
{
public delegate void Mydelegate(int value);
public class Employee
{
public string name;
public string designation;
public string department;
public string salary;
public Mydelegate PassValDelegate;
public void setEmployee(string _setname, string _setdesignation, string _setdepartment, string _setsalary)
{
name = _setname;
designation = _setdesignation;
department = _setdepartment;
salary = _setsalary;
}
public void setSalary()
{
Console.Clear();
Console.WriteLine("Please provide the hike in salary and press enter:");
int hike = Convert.ToInt32(Console.ReadLine().ToString());
int Reviewedsalary = Convert.ToInt32(salary) + hike;
PassValDelegate(Reviewedsalary);
}
public void displayname()
{
Console.WriteLine("Name of the employee is : "+ name);
}
public void displaydesignation()
{
Console.WriteLine("Designation of the employee is : " + designation);
}
public void displaydepartment()
{
Console.WriteLine("Department of the employee is : " + department);
}
public void displaysalary()
{
Console.WriteLine("Salary of the employee is : " + salary + " Dollars");
}
}
}
Now go to program.cs file of your console application and write the methods as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace PassValBetThreads
{
class Program
{
public static int flag = 0;
public delegate void MethodPointer();
static void Main(string[] args)
{
int choice = 0;
Employee Sam = new Employee();
Sam.setEmployee("Sameer Shaik", "Programmer", "IT Development", "5000");
while (choice != 6)
{
if (flag == 0)
{
Console.WriteLine("Please enter 1 to view name of employee");
Console.WriteLine("Please enter 2 to view designation of employee");
Console.WriteLine("Please enter 3 to view department of employee");
Console.WriteLine("Please enter 4 to view salary of employee");
Console.WriteLine("Plese enter 5 to change the salary of the employee");
Console.WriteLine("Please enter 6 to exit");
choice = Convert.ToInt32(Console.ReadLine().ToString());
if (choice == 1)
{
MethodPointer PointerToNameDisplay = new MethodPointer(Sam.displayname);
displayinformation(PointerToNameDisplay);
}
if (choice == 2)
{
MethodPointer PointerToDesignationDisplay = new MethodPointer(Sam.displaydesignation);
displayinformation(PointerToDesignationDisplay);
}
if (choice == 3)
{
MethodPointer PointerToDepartmentDisplay = new MethodPointer(Sam.displaydepartment);
displayinformation(PointerToDepartmentDisplay);
}
if (choice == 4)
{
MethodPointer PointerToSalaryDisplay = new MethodPointer(Sam.displaysalary);
displayinformation(PointerToSalaryDisplay);
}
if (choice == 5)
{
flag = 1;
Sam.PassValDelegate = new Mydelegate(displaySalary);
Thread t1 = new Thread(new ThreadStart(Sam.setSalary));
t1.Start();
}
}
}
}
public static void displayinformation(MethodPointer M1)
{
Console.WriteLine("Displaying information you have chosen");
M1();
Console.WriteLine("Press any key to clear the screen: ");
Console.ReadKey();
Console.Clear();
}
public static void displaySalary(int salary)
{
Console.WriteLine("Renewed salary of the employee is : "+salary );
Console.WriteLine("Press any key to clear the screen: ");
Console.ReadKey();
Console.Clear();
flag = 0;
}
}
}
The above example must clear your understanding on passing and retrieving values from threads.
Passing data to threads C# example
Passing data to Threads:
To pass data to threads, you need to store the data to variables of class when you call constructor.First in your class create a constructor with parameters whose values will be needed by threads.
For example:
class employee
{
//Class Variables
public string name;
public string designation;
public string department;
public string salary;
//My employee constructor
public Employee()
{
name = "Sameer";
designation = "Programmer";
department = "IT";
salary = "3000";
}
}
Now the above class has 4 variables whose values can be passed to any thread like this:
Am going to run a thread on below method, please see the definition
public void displayname()
{
Console.WriteLine("Name of the employee is : "+ name);
}
Now am going to create the thread as follows:
//Create a thread on displayname method
Thread t1 = new Thread(new ThreadStart(displayname));
//Start the thread as follows
t1.Start();
If you check carefully, i haven't passed any parameters to method displayname. The only way to pass values to threads is by using public variables, the way its used in this example.
Please dont confuse yourself alot with this example. Start creating your own class and method. Passing values to thread should be piece of a cake.
Am going to post a detailed post on passing and retrieving values from threads in the next post. If you have any doubts on this, get back to me.
Regards
Sameer Shaik
Check out the video on this post:
Wednesday, June 9, 2010
Managing Threads Simple Example using C#.NET
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ManageThreadExample
{
class Program
{
public static int i = 0;
static void Main(string[] args)
{
Thread DisplayThread = new Thread(new ThreadStart(display));
DisplayThread.Start();
Console.WriteLine("Main Thread is sleeping for 20 seconds");
Thread.Sleep(20000);
Console.WriteLine("DisplayThread is suspended for 5 seconds");
DisplayThread.Suspend();
Thread.Sleep(5000);
Console.WriteLine("DisplayThread is resumed for 40 seconds");
DisplayThread.Resume();
Thread.Sleep(20000);
Console.WriteLine("DisplayThread is Aborted");
DisplayThread.Abort();
Thread.Sleep(3000);
}
public static void display()
{
for (i = 1; i < 10; i++)
{
Console.WriteLine("Displaying while the thread stops me for " + i + " time/times");
int sleeptime = i * 1000;
Thread.Sleep(sleeptime);
int Totaltime = 0;
Totaltime = Totaltime + i;
Console.WriteLine("Sleeping for " + Totaltime + " Seconds");
int TimeThroughout = Totaltime + i + (sleeptime / 1000);
Console.WriteLine("Time spent so far : " + TimeThroughout );
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ManageThreadExample
{
class Program
{
public static int i = 0;
static void Main(string[] args)
{
Thread DisplayThread = new Thread(new ThreadStart(display));
DisplayThread.Start();
Console.WriteLine("Main Thread is sleeping for 20 seconds");
Thread.Sleep(20000);
Console.WriteLine("DisplayThread is suspended for 5 seconds");
DisplayThread.Suspend();
Thread.Sleep(5000);
Console.WriteLine("DisplayThread is resumed for 40 seconds");
DisplayThread.Resume();
Thread.Sleep(20000);
Console.WriteLine("DisplayThread is Aborted");
DisplayThread.Abort();
Thread.Sleep(3000);
}
public static void display()
{
for (i = 1; i < 10; i++)
{
Console.WriteLine("Displaying while the thread stops me for " + i + " time/times");
int sleeptime = i * 1000;
Thread.Sleep(sleeptime);
int Totaltime = 0;
Totaltime = Totaltime + i;
Console.WriteLine("Sleeping for " + Totaltime + " Seconds");
int TimeThroughout = Totaltime + i + (sleeptime / 1000);
Console.WriteLine("Time spent so far : " + TimeThroughout );
}
}
}
}
Wednesday, June 2, 2010
Threads example in C#.NET Complex Example
1.Create two namespaces.
Explanation: Go to file and click on create new project, from the list of options select 'Console Application'. I have named my console application as 'ThreadsExample'.Now you will see on the right, a solution explorer which displays your console application. Your solution has just one project. To add another project to your solution, right click on 'Solution 'ThreadsExample'' select Add-->Add New Project--> Select a console application and name it as 'Consulting Console'.Great good work. Now you have got 2 projects in your solution.
My idea is to display the mechanism of communicating from one console to another console.
2.Define First namespace as
//Open Program.cs in ThreadsExample project and Paste this code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsultingConsole;
using System.Threading;
namespace ThreadsExample
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type the message you want to send to other console:");
string inputfromC1 = Console.ReadLine();
object c1 = (object)inputfromC1;
ThreadPool.QueueUserWorkItem(SendToConsole2,c1);
Console.WriteLine("Console 1 is waiting for the key however i can still display stuff");
Console.ReadKey();
}
public static void SendToConsole2(object _input)
{
string _strinput = (string)_input;
_strinput = "Console-1 Says: " + _input;
Console.WriteLine("Executing Thread While Console 1 is waiting for key ");
Console.WriteLine("Calling Console2:");
ConsultingConsole.Program.o1 = (object)_strinput;
ConsultingConsole.Program.Main();
Console.ReadKey();
Console.WriteLine("Console2 Has finished executing..cool");
Console.ReadKey();
}
}
}
2.Define the other namespace as follows :
//Open program.cs in 'ConsultingConsole' project and paste this code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsultingConsole
{
public class Program
{
public static object o1 = new object();
public static void Main()
{
ThreadPool.QueueUserWorkItem(RecvFromConsole1, o1);
}
public static void RecvFromConsole1(object _input)
{
string _strinput = (string) _input;
Console.WriteLine( _strinput);
Console.WriteLine("Finally Reached Console 2");
Console.ReadKey();
}
}
}
3. To actual see it working, debug your application and check out how cool is threading!!!
Explanation : Let me explain something about threads before we execute the above example. Threads run in background as well as foreground. Imagine i have a multimedia application which plays audio and video. When the user inserts a DVD in his ROM while he is listening to music, the multimedia application will be checking the DVD for any multimedia content. However multimedia application cannot stop playing the music while checking the DVD. Both these tasks must be carried out simultaneously. While the user is listening to songs, software checks the DVD, if there is any content which can be played, then the it should display all the possible options to the user, all of these tasks must be done background. So to achieve multi tasking, we can use threads. So here in this example, the console-1 is waiting for input from user, during this time the method SendToConsole2(object _input) is run in the background. If you know how to debug, just check how amazing the whole idea is!!!, Else i know you wouldn't understand a thing.
4. Am going to update this post very soon. I will provide many simple threading example for you to understand real soon, so keep checking
Regards
Sameer Shaik
Free MCTS EXAM 70-536 training tutorials on this website, soon will be launching video tutorials for all the same topics
http://www.youtube.com/watch?v=2KOcypWILxA
Explanation: Go to file and click on create new project, from the list of options select 'Console Application'. I have named my console application as 'ThreadsExample'.Now you will see on the right, a solution explorer which displays your console application. Your solution has just one project. To add another project to your solution, right click on 'Solution 'ThreadsExample'' select Add-->Add New Project--> Select a console application and name it as 'Consulting Console'.Great good work. Now you have got 2 projects in your solution.
My idea is to display the mechanism of communicating from one console to another console.
2.Define First namespace as
//Open Program.cs in ThreadsExample project and Paste this code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsultingConsole;
using System.Threading;
namespace ThreadsExample
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type the message you want to send to other console:");
string inputfromC1 = Console.ReadLine();
object c1 = (object)inputfromC1;
ThreadPool.QueueUserWorkItem(SendToConsole2,c1);
Console.WriteLine("Console 1 is waiting for the key however i can still display stuff");
Console.ReadKey();
}
public static void SendToConsole2(object _input)
{
string _strinput = (string)_input;
_strinput = "Console-1 Says: " + _input;
Console.WriteLine("Executing Thread While Console 1 is waiting for key ");
Console.WriteLine("Calling Console2:");
ConsultingConsole.Program.o1 = (object)_strinput;
ConsultingConsole.Program.Main();
Console.ReadKey();
Console.WriteLine("Console2 Has finished executing..cool");
Console.ReadKey();
}
}
}
2.Define the other namespace as follows :
//Open program.cs in 'ConsultingConsole' project and paste this code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsultingConsole
{
public class Program
{
public static object o1 = new object();
public static void Main()
{
ThreadPool.QueueUserWorkItem(RecvFromConsole1, o1);
}
public static void RecvFromConsole1(object _input)
{
string _strinput = (string) _input;
Console.WriteLine( _strinput);
Console.WriteLine("Finally Reached Console 2");
Console.ReadKey();
}
}
}
3. To actual see it working, debug your application and check out how cool is threading!!!
Explanation : Let me explain something about threads before we execute the above example. Threads run in background as well as foreground. Imagine i have a multimedia application which plays audio and video. When the user inserts a DVD in his ROM while he is listening to music, the multimedia application will be checking the DVD for any multimedia content. However multimedia application cannot stop playing the music while checking the DVD. Both these tasks must be carried out simultaneously. While the user is listening to songs, software checks the DVD, if there is any content which can be played, then the it should display all the possible options to the user, all of these tasks must be done background. So to achieve multi tasking, we can use threads. So here in this example, the console-1 is waiting for input from user, during this time the method SendToConsole2(object _input) is run in the background. If you know how to debug, just check how amazing the whole idea is!!!, Else i know you wouldn't understand a thing.
4. Am going to update this post very soon. I will provide many simple threading example for you to understand real soon, so keep checking
Regards
Sameer Shaik
Free MCTS EXAM 70-536 training tutorials on this website, soon will be launching video tutorials for all the same topics
http://www.youtube.com/watch?v=2KOcypWILxA
Subscribe to:
Posts (Atom)