web analytics
Working with Threading in C# Options
codeling
Posted: Wednesday, September 27, 2017 11:13:20 PM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 919
Points: 3861

Understanding the Thread States in the .Net

With the .NET Framework, you can easily write applications that perform multiple tasks simultaneously. Tasks with the potential of holding up other tasks can execute on separate threads, a process known as multithreading or free threading. Applications that use multithreading are more responsive to user input because the user interface stays active while processor-intensive tasks execute on separate threads. Multithreading is also useful when creating scalable applications, because you can add threads as the workload increases.

Before you start writing your application in multithreading, it is important for you to understand all possible execution states for threads. The ThreadState property in the Thread class provides these information about a thread. Once a thread is created, it is in at least one of the states until it terminates. Threads created within the common language runtime are initially in the Unstarted state, while external threads that come into the runtime are already in the Running state. An Unstarted thread is transitioned into the Running state by calling Start. Not all combinations of ThreadState values are valid; for example, a thread cannot be in both the Aborted and Unstarted states.

The following table and figure show the actions that cause a change of state.

Action ThreadState
A thread is created within the common language runtime. Unstarted
A thread calls Start Running
The thread starts running. Running
The thread calls Sleep WaitSleepJoin
The thread calls Wait on another object. WaitSleepJoin
The thread calls Join on another thread. WaitSleepJoin
Another thread calls Interrupt Running
Another thread calls Suspend SuspendRequested
The thread responds to a Suspend request. Suspended
Another thread calls Resume Running
Another thread calls Abort AbortRequested
The thread responds to a Abort request. Aborted, then Stopped
A thread is terminated. Stopped

 

In addition to the states noted above, there is also the Background state, which indicates whether the thread is running in the background or foreground.

A thread can be in more than one state at a given time. For example, if a thread is blocked on a call to Wait, and another thread calls Abort on the blocked thread, the blocked thread will be in both the WaitSleepJoin and the AbortRequested states at the same time. In this case, as soon as the thread returns from the call to Wait or is interrupted, it will receive the ThreadAbortException to begin aborting.

The Thread.ThreadState property of a thread provides the current state of a thread. Since the value for Running is zero (0), applications must use a bitmask to determine whether a thread is running:

(myThread.ThreadState & (ThreadState.Stopped | ThreadState.Unstarted)) == 0

The following table lists the value of all the states of a thread.

Member name Description Value
Aborted The thread is in the Stopped state. 256
AbortRequested The Thread.Abort method has been invoked on the thread, but the thread has not yet received the pending System.Threading.ThreadAbortException that will attempt to terminate it. 128
Background The thread is being executed as a background thread, as opposed to a foreground thread. This state is controlled by setting the Thread.IsBackground property. 4
Running The thread has been started, it is not blocked, and there is no pending ThreadAbortException. 0
Stopped The thread has stopped. 16
StopRequested The thread is being requested to stop. This is for internal use only. 1
Suspended The thread has been suspended. 64
SuspendRequested The thread is being requested to suspend. 2
Unstarted The Thread.Start method has not been invoked on the thread. 8
WaitSleepJoin The thread is blocked as a result of a call to Wait, Sleep, or Join. 32

The following C# code shows how the thread changes its status when different methods are called.

 class ThreadStateExample {
  static void Main() {
    Thread t = new Thread (delegate() { while (true); });
    Console.WriteLine (t.ThreadState);     // Unstarted
 
    t.Start();
    Thread.Sleep (1000);
    Console.WriteLine (t.ThreadState);     // Running
 
    t.Abort();
    Console.WriteLine (t.ThreadState);     // AbortRequested
 
    t.Join();
    Console.WriteLine (t.ThreadState);     // Stopped
  }
}
Sponsor
Posted: Wednesday, September 27, 2017 11:13:20 PM
codeling
Posted: Wednesday, September 27, 2017 11:18:22 PM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 919
Points: 3861

Creating threads in C#

The Thread class that belongs to the System.Threading namespace contains the necessary members for creating, suspending, resuming and aborting threads.

using System;
using System.Threading;
 
class Test
{
  static void MyThreadMethod()
  {
    Console.WriteLine("This is the workerthread.");
  }
 
  static void Main()
  {
    Console.WriteLine("This is the main orthe primary thread of the application.");

    Thread t = new Thread(newThreadStart(MyThreadMethod));

    t.Start();
     
  }
}

When the thread object is first created it is in the Unstarted state.  The Start() method is responsible for starting the thread.  Remember that when we start a thread it might not be immediately started. To be specific, it is actually put in the ready or the runnable state. It is the responsibility of the Operating System to actually schedule the thread from the runnable state to the running state. The method MyThreadMethod() contains the actual thread code that would be executed once a call to the Start() method is made.  It should be remembered that the following should hold good for a method to be a thread method.

  • It should have no parameters.
  • It should have a void return type.
codeling
Posted: Wednesday, September 27, 2017 11:24:41 PM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 919
Points: 3861

Making a Thread to Sleep in C#

In order to put a thread to sleep, the Sleep() method is invoked. This is a blocking call indicating that the thread will resume its execution once the time for which it is made to sleep elapses.

The following code makes the thread to sleep for 5 seconds.

Thread.Sleep(5000);

To make a thread sleep infinitely use the following code.

Thread.Sleep(Timeout.Infinite); or

Thread.Sleep(Timeout.InfiniteTimeSpan);

You can specify Timeout.Infinite for the millisecondsTimeout parameter to suspend the thread indefinitely. However, we recommend that you use other System.Threading classes such as Mutex, Monitor, EventWaitHandle, or Semaphore instead to sychronize threads or manage resources.

codeling
Posted: Thursday, September 28, 2017 10:14:11 AM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 919
Points: 3861

Synchronization in Threads

Join() method is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate. In the following example, the Thread1 thread calls the Join() method of Thread2, which causes Thread1 to block until Thread2 has completed.

 
using System;
using System.Threading;

public class Example
{
   static Thread thread1, thread2;
   
   public static void Main()
   {
      thread1 = new Thread(ThreadProc);
      thread1.Name = "Thread1";
      thread1.Start();
      
      thread2 = new Thread(ThreadProc);
      thread2.Name = "Thread2";
      thread2.Start();   
   }

   private static void ThreadProc()
   {
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      if (Thread.CurrentThread.Name == "Thread1" && 
          thread2.ThreadState != ThreadState.Unstarted)
         thread2.Join();
      
      Thread.Sleep(4000);
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      Console.WriteLine("Thread1: {0}", thread1.ThreadState);
      Console.WriteLine("Thread2: {0}\n", thread2.ThreadState);
   }
}
// The example displays output like the following:
//       Current thread: Thread1
//       
//       Current thread: Thread2
//       
//       Current thread: Thread2
//       Thread1: WaitSleepJoin
//       Thread2: Running
//       
//       
//       Current thread: Thread1
//       Thread1: Running
//       Thread2: Stopped
 

If the thread has already terminated when Join is called, the method returns immediately.

Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2017 Digcode.com. All rights reserved.