IT Community - Software Programming, Web Development and Technical Support

Threading in C# .Net 2005 :

This is a discussion on Threading in C# .Net 2005 : within the C# Programming forums, part of the Software Development category; Hi All, This thread is to share the issues, basic ideas and examples , etc... about Threads in .net............... A thread ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Software Development > C# Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 09-10-2007, 06:07 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Threading in C# .Net 2005 :

Hi All,

This thread is to share the issues, basic ideas and examples , etc... about Threads in .net...............

A thread is short for a thread of execution. Threads are a way for a program to fork (or split) itself into two or more simultaneously (or pseudo-simultaneously) running tasks. Threads and processes differ from one operating system to another, but in general, the way that a thread is created and shares its resources is different from the way a process does.

Multiple threads can be executed in parallel on many computer systems. This multithreading generally occurs by time slicing (similar to time-division multiplexing), wherein a single processor switches between different threads, in which case the processing is not literally simultaneous, for the single processor is really doing only one thing at a time. This switching can happen so fast as to give the illusion of simultaneity to an end user. For instance, many PCs today only contain one processor core, but one can run multiple programs at once, such as typing in a document editor while listening to music in an audio playback program; though the user experiences these things as simultaneous, in truth, the processor quickly switches back and forth between these separate processes. On a multiprocessor or multi-core system, now coming into general use, threading can be achieved via multiprocessing, wherein different threads and processes can run literally simultaneously on different processors or cores.

Many modern operating systems directly support both time-sliced and multiprocessor threading with a process scheduler. The operating system kernel allows programmers to manipulate threads via the system call interface. Some implementations are called a kernel thread, whereas a lightweight process is a specific type of kernel thread that shares the same state and information.

thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 09-10-2007, 06:10 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default What is thread?

Hi Deeban,

Iam a newbie to .net can you explain what is thread?


thanks in advance...
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 09-10-2007, 06:11 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default What is thread?

Hi Sathish...

C# supports parallel execution of code through multithreading. A
thread is an independent execution path, able to run simultaneously
with other threads.
A C# program starts in a single thread created automatically by the
CLR and operating system (the "main" thread), and is made multithreaded
by creating additional threads.

thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 09-10-2007, 06:12 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default what are the namespaces used for threading...?

Hi deeban,

what are the namespaces used for threading...?

thnx...
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 09-10-2007, 06:14 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Sathish...

the namespaces used for threading are..

System;
System.Threading;


thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 09-10-2007, 06:15 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Deeban,

Thanks for your reply...

can you give me simple example for threading...


thanks...
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 09-10-2007, 06:18 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Sathish...

class ThreadTest {
static void Main() {
Thread t = new Thread (WriteY);
t.Start(); // Run WriteY on the new thread
while (true) Console.Write ("x"); // Write 'x' forever
}
static void WriteY() {
while (true) Console.Write ("y"); // Write 'y' forever
}
}

The main thread creates a new thread t on which it runs a method that repeatedly prints the
character y. Simultaneously, the main thread repeatedly prints the character x.
The CLR assigns each thread its own memory stack so that local variables are kept separate. In
the next example, we define a method with a local variable, then call the mehtod simultaneously
on the main thread and a newly created thread:
static void Main() {
new Thread (Go).Start(); // Call Go() on a new thread
Go(); // Call Go() on the main thread
}
static void Go() {
// Declare and use a local variable - 'cycles'
for (int cycles = 0; cycles < 5; cycles++) Console.Write ('?');
}


A separate copy of the cycles variable is created on each thread's memory stack, and so the output
is, predictably, ten question marks.
Threads share data if they have a common reference to the same object instance. Here's an
example:
class ThreadTest {
bool done;
static void Main() {
ThreadTest tt = new ThreadTest(); // Create a common instance
new Thread (tt.Go).Start();
tt.Go();
}
// Note that Go is now an instance method
void Go() {
if (!done) { done = true; Console.WriteLine ("Done"); }
}
}
Because both threads call Go() on the same ThreadTest instance, they share the done field. This
results in "Done" being printed once instead of twice:


Static fields offer another way to share data between threads. Here's the same example with done
as a static field:
class ThreadTest {
static bool done; // Static fields are shared between all threads
static void Main() {
new Thread (Go).Start();
Go();
}
static void Go() {
if (!done) { done = true; Console.WriteLine ("Done"); }
}
}

I hope this will help you...

thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 09-10-2007, 06:20 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi deeban...

thanks for your reply...

while i read threading i saw the word thread safty... what is it.. what is it mean...


can you explain...


thanks in advance...
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 09-10-2007, 06:22 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Sathish...

Both of these examples illustrate another key concept – that of thread safety (or, rather, lack of
it!) The output is actually indeterminate: it's possible (although unlikely) that "Done" could be
printed twice. If, however, we swap the order of statements in the Go method, then the odds of
"Done" being printed twice go up dramatically:
static void Go() {
if (!done) { Console.WriteLine ("Done"); done = true; }
}
Done
Done (usually!)
The problem is that one thread can be evaluating the if statement right as the other thread is
executing the WriteLine statement – before it's had a chance to set done to true.
5
The remedy is to obtain an exclusive lock while reading and writing to the common field. C#
provides the lock statement for just this purpose:
class ThreadSafe {
static bool done;
static object locker = new object();
static void Main() {
new Thread (Go).Start();
Go();
}
static void Go() {
lock (locker) {
if (!done) { Console.WriteLine ("Done"); done = true; }
}
}
}
When two threads simultaneously contend a lock (in this case, locker), one thread waits, or
blocks, until the lock becomes available. In this case, it ensures only one thread can enter the
critical section of code at a time, and "Done" will be printed just once. Code that's protected in
such a manner – from indeterminacy in a multithreading context – is called thread-safe.
Temporarily pausing, or blocking, is an essential feature in coordinating, or synchronizing the
activities of threads. Waiting for an exclusive lock is one reason for which a thread can block.
Another is if a thread wants to pause, or Sleep for a period of time:
Thread.Sleep (TimeSpan.FromSeconds (30)); // Block for 30 seconds
A thread can also wait for another thread to end, by calling its Join method:
Thread t = new Thread (Go); // Assume Go is some static method
t.Start();
Thread.Join (t); // Wait (block) until thread t ends
A thread, while blocked, doesn't consume CPU resources.


i hope this will help you...

thnx..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 09-10-2007, 06:23 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Deeban,

thanks for your reply.... can you explain how the threading works...


thanks in advance...
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 09-10-2007, 06:24 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default How Threading Works ?

Hi Sathish...

sure..

Multithreading is managed internally by a thread scheduler, a function the CLR typically
delegates to the operating system. A thread scheduler ensures all active threads are allocated
appropriate execution time, and that threads that are waiting or blocked – for instance – on an
exclusive lock, or on user input – do not consume CPU time.
On a single-processor computer, a thread scheduler performs time-slicing – rapidly switching
execution between each of the active threads. This results in "choppy" behavior, such as in the
very first example, where each block of a repeating X or Y character corresponds to a time-slice
allocated to the thread. Under Windows XP, a time-slice is typically in the tens-of-milliseconds
region – chosen such as to be much larger than the CPU overhead in actually switching context
between one thread and another (which is typically in the few-microseconds region).
On a multi-processor computer, multithreading is implemented with a mixture of time-slicing and
genuine concurrency – where different threads run code simultaneously on different CPUs. It's
almost certain there will still be some time-slicing, because of the operating system's need to
service its own threads – as well as those of other applications.
6
A thread is said to be preempted when its execution is interrupted due to an external factor such
as time-slicing. In most situations, a thread has no control over when and where it's preempted.

thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 09-10-2007, 06:26 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Threads vs. Processes

Hi Deeban,


thanks again...

can you explain what is the difference between Threads vs. Processes.


thanks..
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 09-10-2007, 06:27 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Sathish...

All threads within a single application are logically contained within a process – the operating
system unit in which an application runs.
Threads have certain similarities to processes – for instance, processes are typically time-sliced
with other processes running on the computer in much the same way as threads within a single
C# application. The key difference is that processes are fully isolated from each other; threads
share (heap) memory with other threads running in the same application. This is what makes
threads useful: one thread can be fetching data in the background, while another thread is
displaying the data as it arrives.


i hope this will help you...

thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 09-10-2007, 06:30 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Deeban,


one more doubt...

When to Use Threads, can you explain, now i knew about the threads.. but i dont know, When to Use Threads..... can you explain...?


thanks...
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #15 (permalink)  
Old 09-10-2007, 06:32 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Sathish...

A common application for multithreading is performing time-consuming tasks in the background.
The main thread keeps running, while the worker thread does its background job. With Windows
Forms applications, if the main thread is tied up performing a lengthy operation, keyboard and
mouse messages cannot be processed, and the application becomes unresponsive. For this reason,
it’s worth running time-consuming tasks on worker threads even if the main thread has the user
stuck on a “Processing… please wait” modal dialog in cases where the program can’t proceed
until a particular task is complete. This ensures the application doesn’t get tagged as “Not
Responding” by the operating system, enticing the user to forcibly end the process in frustration!
The modal dialog approach also allows for implementing a "Cancel" button, since the modal
form will continue to receive events while the actual task is performed on the worker thread. The
BackgroundWorker class assists in just this pattern of use.
In the case of non-UI applications, such as a Windows Service, multithreading makes particular
sense when a task is potentially time-consuming because it’s awaiting a response from another
computer (such as an application server, database server, or client). Having a worker thread
perform the task means the instigating thread is immediately free to do other things.
Another use for multithreading is in methods that perform intensive calculations. Such methods
can execute faster on a multi-processor computer if the workload is divided amongst multiple
threads. (One can test for the number of processors via the Environment.ProcessorCount
property).
A C# application can become multi-threaded in two ways: either by explicitly creating and
running additional threads, or using a feature of the .NET framework that implicitly creates
threads – such as BackgroundWorker, thread pooling, a threading timer, a Remoting server, or a
Web Services or ASP.NET application. In these latter cases, one has no choice but to embrace
multithreading. A single-threaded web server would not be cool – even if such a thing were
possible! Fortunately, with stateless application servers, multithreading is usually fairly simple;
one's only concern perhaps being in providing appropriate locking mechanisms around data
cached in static variables.


i hope this will help you...

thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #16 (permalink)  
Old 09-10-2007, 06:33 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default When Not to Use Threads?

Hi Deeban,

thanks for your reply, i understand when to use threads, i have one more doubt is there any other situation for not to use threads...


thanks...
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #17 (permalink)  
Old 09-10-2007, 06:35 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Sathish...

Multithreading also comes with disadvantages. The biggest is that it can lead to vastly more
complex programs. Having multiple threads does not in itself create complexity; it's the
interaction between the threads that creates complexity. This applies whether or not the
interaction is intentional, and can result long development cycles, as well as an ongoing
susceptibility to intermittent and non-reproducable bugs. For this reason, it pays to keep such
interaction in a multi-threaded design simple – or not use multithreading at all – unless you have
a peculiar penchant for re-writing and debugging!
Multithreading also comes with a resource and CPU cost in allocating and switching threads if
used excessively. In particular, when heavy disk I/O is involved, it can be faster to have just one
or two workers thread performing tasks in sequence, rather than having a multitude of threads
each executing a task at the same time. Later we describe how to implement a
Producer/Consumer queue, which provides just this functionality.


i hope this will help you...

thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #18 (permalink)  
Old 09-10-2007, 06:37 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default how to Create and Start Threads ?

Hi Deeban,

thanks for your reply...

how can i create a thread and how to start can you explain ...


thanks in advance...
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #19 (permalink)  
Old 09-10-2007, 06:40 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: Threading in C# .Net 2005 :

Hi Sathis...

Threads are created using the Thread class’s constructor, passing in a ThreadStart delegate –
indicating the method where execution should begin. Here’s how the ThreadStart delegate is
defined:
public delegate void ThreadStart();
Calling Start on the thread then sets it running. The thread continues until its method returns, at
which point the thread ends. Here’s an example, using the expanded C# syntax for creating a
TheadStart delegate:
class ThreadTest {
static void Main() {
Thread t = new Thread (new ThreadStart (Go));
t.Start(); // Run Go() on the new thread.
Go(); // Simultaneously run Go() in the main thread.
}
static void Go() { Console.WriteLine ("hello!"); }
In this example, thread t executes Go() – at (much) the same time the main thread calls Go(). The
result is two near-instant hellos:
hello!
hello!
A thread can be created more conveniently using C#'s shortcut syntax for instantiating delegates:
static void Main() {
Thread t = new Thread (Go); // No need to explicitly use ThreadStart
t.Start();
...
}
static void Go() { ... }
In this case, a ThreadStart delegate is inferred automatically by the compiler. Another shortcut
is to use an anonymous method to start the thread:
8
static void Main() {
Thread t = new Thread (delegate() { Console.WriteLine ("Hello!"); });
t.Start();
}
A thread has an IsAlive property that returns true after its Start() method has been called, up
until the thread ends.
A thread, once ended, cannot be re-started.


thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #20 (permalink)  
Old 09-10-2007, 06:41 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Passing Data to ThreadStart

Hi Deeban,

is there any way to pass arguments to threads.. if yes.. then how can i pass data to threads while it start...

thanks....
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
ASP.net threading issue when populating a listbox $enthil ASP and ASP.NET Programming 6 11-04-2007 11:24 PM
Threading in VB.Net Tips S.Vinothkumar VB.NET Programming 16 10-30-2007 07:55 AM
How to implement threading in VB.Net? amansundar VB.NET Programming 2 10-30-2007 07:41 AM
I Cannot access SQL 2005 integrated services after installing SQL-2005..? theone Database Support 1 07-27-2007 01:12 AM
what is the threading model used for ASP.Net? mobilegeek ASP and ASP.NET Programming 1 07-21-2007 01:48 AM


All times are GMT -7. The time now is 01:36 PM.