Thread sleep demo


   

   using System;
   using System.Threading;

   class ThreadTester
   {
      static void Main( string[] args )
      {
         MessagePrinter printer1 = new MessagePrinter();
         Thread thread1 = new Thread ( new ThreadStart( printer1.Print ) );
         thread1.Name = "thread1";

         MessagePrinter printer2 = new MessagePrinter();
         Thread thread2 = new Thread ( new ThreadStart( printer2.Print ) );
         thread2.Name = "thread2";

         MessagePrinter printer3 = new MessagePrinter();
         Thread thread3 = new Thread ( new ThreadStart( printer3.Print  ) );
         thread3.Name = "thread3";

         Console.WriteLine( "Starting threads" );

         thread1.Start();
         thread2.Start();
         thread3.Start();

         Console.WriteLine( "Threads started
" ); 

      } 
   }
   class MessagePrinter {
      public void Print() 
      {
         Thread current = Thread.CurrentThread; 
         Console.WriteLine(current.Name + " going to sleep" );
         Thread.Sleep ( 4000 );
         Console.WriteLine( current.Name + " done sleeping" );
      } 
   }



           
          


Use IsAlive to wait for threads to end

   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
using System;

// Use IsAlive to wait for threads to end. 
public class MoreThreads2 { 
  public static void Main() { 
    Console.WriteLine("Main thread starting."); 
 
    // Construct three threads. 
    MyThread mt1 = new MyThread("Child #1"); 
    MyThread mt2 = new MyThread("Child #2"); 
    MyThread mt3 = new MyThread("Child #3"); 
 
    do { 
      Console.Write("."); 
      Thread.Sleep(100); 
    } while (mt1.thrd.IsAlive && 
             mt2.thrd.IsAlive && 
             mt3.thrd.IsAlive); 
 
    Console.WriteLine("Main thread ending."); 
  } 
}


           
          


Current Thread Properties

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

class Program {
static int interval;
static void Main(string[] args) {
interval = 100;

ThreadPool.QueueUserWorkItem(new WaitCallback(StartMethod));
Thread.Sleep(100);
ThreadPool.QueueUserWorkItem(new WaitCallback(StartMethod));
Console.ReadLine();

}

static void StartMethod(Object stateInfo) {
DisplayNumbers(“Thread ” + DateTime.Now.Millisecond.ToString());
Console.WriteLine(“Thread Finished”);
}

static void DisplayNumbers(string GivenThreadName) {
Console.WriteLine(“Starting thread: ” + GivenThreadName);

for (int i = 1; i <= 8 * interval; i++) { if (i % interval == 0) { Console.WriteLine("Count has reached " + i); Console.WriteLine("CurrentCulture: " + Thread.CurrentThread.CurrentCulture.ToString()); Console.WriteLine("IsThreadPoolThread: " + Thread.CurrentThread.IsThreadPoolThread.ToString()); Console.WriteLine("ManagedThreadId: " + Thread.CurrentThread.ManagedThreadId.ToString()); Console.WriteLine("Priority: " + Thread.CurrentThread.Priority.ToString()); Console.WriteLine("ThreadState: " + Thread.CurrentThread.ThreadState.ToString()); Thread.Sleep(1000); } } } } [/csharp]

Thread Pool Tcp Server

   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class ThreadPoolTcpSrvr
{
   private TcpListener client;

   public ThreadPoolTcpSrvr()
   {
      client = new TcpListener(9050);
      client.Start();

      Console.WriteLine("Waiting for clients...");
      while(true)
      {
         while (!client.Pending())
         {
            Thread.Sleep(1000);
         }
         ConnectionThread newconnection = new ConnectionThread();
         newconnection.threadListener = this.client;
         ThreadPool.QueueUserWorkItem(new
                    WaitCallback(newconnection.HandleConnection));
      }
   }

   public static void Main()
   {
      ThreadPoolTcpSrvr tpts = new ThreadPoolTcpSrvr();
   }
}

class ConnectionThread
{
   public TcpListener threadListener;
   private static int connections = 0;

   public void HandleConnection(object state)
   {
      int recv;
      byte[] data = new byte[1024];

      TcpClient client = threadListener.AcceptTcpClient();
      NetworkStream ns = client.GetStream();
      connections++;
      Console.WriteLine("New client accepted: {0} active connections",
                         connections);

      string welcome = "Welcome to my test server";
      data = Encoding.ASCII.GetBytes(welcome);
      ns.Write(data, 0, data.Length);

      while(true)
      {
         data = new byte[1024];
         recv = ns.Read(data, 0, data.Length);
         if (recv == 0)
            break;
      
         ns.Write(data, 0, recv);
      }
      ns.Close();
      client.Close();
      connections--;
      Console.WriteLine("Client disconnected: {0} active connections",
                         connections);
   }
}

           
          


ThreadPool.QueueUserWorkItem

using System;
using System.Threading;

class WinterLocked {
public ManualResetEvent a = new ManualResetEvent(false);
private int i = 5;

public void Run(object s) {
Interlocked.Increment(ref i);
Console.WriteLine(“{0} {1}”,
Thread.CurrentThread.GetHashCode(), i);
}
}

public class MainApp {
public static void Main() {
ManualResetEvent mR = new ManualResetEvent(false);
WinterLocked wL = new WinterLocked();
for (int i = 1; i <= 10; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(wL.Run), 1); } mR.WaitOne(10000, true); } } [/csharp]

ThreadPool.RegisterWaitForSingleObject

   
 
using System;
using System.Threading;

class MainClass
{
    private static void EventHandler(object state, bool timedout)
    {
        if (timedout)
        {
            Console.WriteLine("{0} : Wait timed out.", DateTime.Now.ToString("HH:mm:ss.ffff"));
        }
        else
        {
            Console.WriteLine("{0} : {1}", DateTime.Now.ToString("HH:mm:ss.ffff"), state);
        }
    }

    public static void Main()
    {
        AutoResetEvent autoEvent = new AutoResetEvent(false);
        string state = "AutoResetEvent signaled.";
        RegisteredWaitHandle handle = ThreadPool.RegisterWaitForSingleObject(autoEvent, EventHandler, state, 3000, false);

        while (Console.ReadLine().ToUpper() != "CANCEL")
        {
            autoEvent.Set();
        }
        Console.WriteLine("Unregistering wait operation.");
        handle.Unregister(null);
    }
}

    


Threading Class Monitor

   

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
using System.Collections;
using System.Threading;

namespace Client.Chapter_15___Threading
{
  public class ThreadingClassMonitor
  {
    public static Thread ThreadOne = ThreadOne = new Thread(new ThreadStart(MonitorExample));
    public static ArrayList MyList = new ArrayList();
    public ThreadingClassMonitor()
    {
      MyList.Add("Test1");
      MyList.Add("Test2");
    }
    static void Main(string[] args)
    {
      ThreadOne.Start();
    }
    protected static void MonitorExample()
    {
      Monitor.Enter(MyList);
      MyList.Add("Test3");
      Monitor.Exit(MyList);
    }
  }
}