Homei use portalCalendarGalleryFAQMemberlistSearchUsergroupsRegisterLog in

Share | 

 [TUT] For first timers in threading

Go down 
Bronze Marketer
Bronze Marketer

Posts : 37
Reputation : 0
Join date : 2012-06-26

PostSubject: [TUT] For first timers in threading   Wed Jul 18, 2012 8:24 am

(I assume that the reader of this thread has some primery knowledge of .net framework and using visual studio.)
Threading is the ability of a development framework to spin off parts of an application into "threads", which run out of step with the rest of the program. In most programming languages, you have the equivalent of a Main () method, and each line is executed in sequence, with the next line executing only after the previous has completed. A thread is a special object that is part of the general multitasking abilities of an operating system and allows a part of the application to run independently from the execution of other objects, and so out of the general execution sequence of the application.

There are lots to discuss when you want to learn about threading. I will try to give you a concise guide to learn the first steps of threading. Before proceeding to actually creating threads lets review some thread related concepts.

Process is the operating system unit in which an application runs. When an application is launched, memory and any other resource for that application are allocated. The physical separation of this memory and resources is called a process. Of course, the application may launch more than one process. It's important to note that the words "application" and "process" are not synonymous. The memory allocated to the process is isolated from that of other processes and only that process is allowed to access it. Inter process communication is possible but that is a whole new chapter.

A thread is an independent execution path, able to run simultaneously with other threads. In other words, an execution sequence used by the process is called thread. This thread is defined by the registers in use on the CPU, the stack used by the thread, and a container that keeps track of the thread's current state. The container mentioned in the last sentence is known as Thread Local Storage. C# supports parallel execution of code through multithreading.

Single-Threaded Processes
Each process has at least one of these sequential execution orders, or threads. Creating a process includes starting the process running at a point in the instructions. This initial thread is known as the primary or main thread. The thread's actual execution sequence is determined by what you code in your application's methods. For instance, in a simple .NET Windows Forms application, the primary thread is started in the static Main () method placed in your project. It begins with a call to Application.Run().

Time Slices
The processor actually grants time to the process. The period that the process can execute is known as a time slice or a quantum. The period of this time slice is unknown to the programmer and unpredictable to anything besides the operating system. Programmers should not consider this time slice as a constant in their applications. Each operating system and each processor may have a different time allocated.

Multithreaded Processes
We can split up our process to share the time slice allotted to it. This happens by spawning additional threads of execution within the process. You may spawn an additional thread in order to do some background work, such as accessing a network or querying a database. Because these secondary threads are usually created to do some work, they are commonly known as worker threads. These threads share the process's memory space that is isolated from all the other processes on the system. The concept of spawning new threads within the same process is known as free threading.

System.Threading Namespace Thread Class
Threads in managed code are represented by a System.Threading.Thread class instance.
Thread class represents our processing threads. This class allows us to do everything, from managing a thread's priority, to reading its status.
Let's start by looking at a list of this class's public methods.
Abort() This overloaded method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.
AllocateDataSlot() This static method allocates an unnamed data slot on all the threads.
AllocateNamedDataSlot() This static method allocates a named data slot on all threads.
FreeNamedDataSlot() This static method frees a previously allocated named data slot.
GetData() This static method retrieves the value from the specified slot on the current thread, within the current thread's current domain.
GetDomain() This static method returns the current domain in which the current thread is running.
GetDomainID() This static method returns a unique application domain identifier.
GetHashCode() This method serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
GetNamedDataSlot() This static method looks up a named data slot.
Interrupt() This method interrupts a thread that is in the WaitSleepJoin thread state.
Join() This overloaded method blocks the calling thread until a thread terminates.
ResetAbort() This static method cancels an Abort() requested for the current thread.
Resume() This method resumes a thread that has been suspended.
SetData() This static method sets the data in the specified slot on the currently running thread, for that thread's current domain.
Sleep() This static and overloaded method blocks the current thread for the specified number of milliseconds.
SpinWait() This static method causes a thread to wait the number of times defined by the iterations parameter.
Start() This method causes the operating system to change the state of the current instance to ThreadState.Running.
Suspend() This method will either suspend the thread, or if the thread is already suspended, has no effect.
Now let's look at another list, this time containing its public properties.
ApartmentState Sets or gets the apartment state of this thread.
CurrentContext This static property gets the current context in which the thread is executing.
CurrentCulture Sets or gets the culture for the current thread.
CurrentPrincipal This static property sets or gets the thread's current principal. It is used for role-based security.
CurrentThread This static property gets the currently running thread.
CurrentUICulture Used at run time, this property sets or gets the current culture used by the Resource Manager to look up culture-specific resources.
IsAlive Gets a value that indicates the execution status of the current thread.
IsBackground Sets or gets a value that indicates whether a thread is a background thread or not.
IsThreadPoolThread Gets a value indicating whether a thread is part of a thread pool.
Name Sets or gets the name of the thread.
Priority Sets or gets a value that indicates the scheduling priority of a thread.
ThreadState Gets a value that contains the states of the current thread.
Creating and Starting Threads
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

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:
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
static void Go() { ... }

In this case, a ThreadStart delegate is inferred automatically by the compiler.
Hear is a more extended example:

using System;
  using System.Threading;

  public class SimpleThreadExample
      public static Thread worker;
      public static Thread worker2;

      public static void Main()
        Console.WriteLine("Entering the void Main!");

        worker = new Thread(new ThreadStart(Counter));
        worker2 = new Thread(new ThreadStart(Counter2));


        Console.WriteLine("Exiting the void Main!");

      public static void Counter()
        Console.WriteLine("Entering Counter");
        for(int i = 1; i < 50; i++)
            Console.Write(i + " ");
            if(i == 10)
        Console.WriteLine("Exiting Counter");

      public static void Counter2()
        Console.WriteLine("Entering Counter2");
        for(int i = 51; i < 100; i++)
            Console.Write(i + " ");
            if( i == 70 )
        Console.WriteLine("Exiting Counter2");

The Counter() method counts numbers from 1 to 50 and when it reaches 10 it sleeps for 1000 milliseconds. The Counter2() method counts from 51 to 100 and when it reaches 70 it sleeps for 5000 milliseconds. Here is how the output might look:
Entering the void Main!
Entering Counter2
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 Exiting
the void Main!
Entering Counter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
Exiting Counter
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
94 95 96 97 98 99 100
Exiting Counter2
Background Processes
The first opportunity to spawn a new thread occurs when your application needs to run a large process in the background while still keeping its user interface active and usable. We have all run into times when an application just didn't seem to respond because we had told it to query data or process a large piece of information.

Let's take a look at an example of a background process that needs to spawn a new thread. This example demonstrates searching for files. When the search routine finds a file matching the pattern specified, it adds a new item to the ListBox. The code below will demonstrate that this method does indeed need its own thread:
Start a new project in C#.
Create following controls:
a. CmdSingle (add click event)
b. CmdMulti (add click event)
c. ListBox1
d. TextBox1
Put this code in your from source code.

using System.Threading;
  using System.IO;
  public class Threaded Search : System.Windows.Forms.Form
    string search;
    int fileCount;
    private void cmdSingle Click(object sender, System.EventArgs e)
  private void cmdMulti Click(object sender, System.EventArgs e)
    Thread t = new Thread(new ThreadStart(Search));

    public void Search()
      search = TextBox1.Text;
      fileCount = 0;

    public void SearchDirectory(string Path)
      // Search the directory
      DirectoryInfo di = new DirectoryInfo(Path);
      FileInfo[] f = di.GetFiles(search);


      foreach(FileInfo myFile in f)


      // Search its sub directories
      DirectoryInfo[] d = di.GetDirectories();

      foreach(DirectoryInfo myDir in d)

Go ahead and compile this example and run it. Type a search term in the search textbox, such as * . *, click the Single Thread Search button, and observe our problem. As you will see, we are searching for files and trying to update the user interface every time we find a file with our search criteria. However, because both the user interface and the search code are running on the same thread, we don't see the updates until the search code has completely finished its processing. Additionally, we cannot resize our form while the search is processing.

Now, click the Multi Thread Search button. You can see that there is quite a difference. This time our results are displayed immediately. This is because Windows is now switching execution back and forth between the user interface and the search thread. The processor is now given a time slice to update the interface to reflect the changes in the ListBox. You will also notice that we can now resize our form while it is searching.

There is lot more to know about threading. I hope that above will be helpful for you to get first grasp of threading.
Back to top Go down
View user profile
[TUT] For first timers in threading
Back to top 
Page 1 of 1

Permissions in this forum:You cannot reply to topics in this forum
Money Dreamer Forum :: Programming, Computing and Graphics :: Programming-
Jump to: