c# performance effect of threading

 

new WaitCallback

using System;
using System.Threading;

class ThreadPoolDemo {
public void LongTask1(object obj) {
for (int i = 0; i <= 999; i++) { Console.WriteLine("Long Task 1 is being executed"); } } public void LongTask2(object obj) { for (int i = 0; i <= 999; i++) { Console.WriteLine("Long Task 2 is being executed"); } } static void Main() { ThreadPoolDemo tpd = new ThreadPoolDemo(); for (int i = 0; i < 50; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.LongTask1)); ThreadPool.QueueUserWorkItem(new WaitCallback(tpd.LongTask2)); } Console.Read(); } } [/csharp]

new ThreadStart

   
 

using System;
using System.Threading;

public class SimpleThread {
    public void SimpleMethod() {
        int result = 1;
        Console.WriteLine(result.ToString() + " from thread ID: " +
                          AppDomain.GetCurrentThreadId().ToString());
    }

    public static void Main() {
        SimpleThread simpleThread = new SimpleThread();
        simpleThread.SimpleMethod();

        ThreadStart ts = new ThreadStart(simpleThread.SimpleMethod);
        Thread t = new Thread(ts);
        t.Start();
    }
}

    


Threading Class Mutex

   

/*
 * 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 ThreadingClassMutex
  {
    public static Thread ThreadOne = new Thread(new ThreadStart(MutexExample));
    public static ArrayList MyList = new ArrayList();
    private static Mutex MyMutex = new Mutex(false, "MyMutex");
    public ThreadingClassMutex()
    {
      MyList.Add("Test1");
      MyList.Add("Test2");
    }
    static void Main(string[] args)
    {
      ThreadOne.Start();
    }
    protected static void MutexExample()
    {
      MyMutex.WaitOne();
      MyList.Add("Test3");
      MyMutex.ReleaseMutex();
    }
  }

}

           
          


A synchronized shared buffer implementation

using System;
using System.Threading;

public class SynchronizedBuffer
{
private int buffer = -1;

private int occupiedBufferCount = 0;

public int Buffer
{
get
{
Monitor.Enter( this );

if ( occupiedBufferCount == 0 )
{
Console.WriteLine(Thread.CurrentThread.Name + ” tries to read.” );
DisplayState( “Buffer empty. ” +Thread.CurrentThread.Name + ” waits.” );
Monitor.Wait( this );
}
–occupiedBufferCount;

DisplayState( Thread.CurrentThread.Name + ” reads ” + buffer );

Monitor.Pulse( this );
int bufferCopy = buffer;

Monitor.Exit( this );

return bufferCopy;
}
set
{
Monitor.Enter( this );
if ( occupiedBufferCount == 1 )
{
Console.WriteLine(Thread.CurrentThread.Name + ” tries to write.” );
DisplayState( “Buffer full. ” + Thread.CurrentThread.Name + ” waits.” );
Monitor.Wait( this );
}
buffer = value;

++occupiedBufferCount;

DisplayState( Thread.CurrentThread.Name + ” writes ” + buffer );
Monitor.Pulse( this );

Monitor.Exit( this );
}
}

public void DisplayState( string operation )
{
Console.WriteLine( “{0,-35}{1,-9}{2}
“,operation, buffer, occupiedBufferCount );
}

static void Main( string[] args )
{
SynchronizedBuffer shared = new SynchronizedBuffer();
Random random = new Random();

Console.WriteLine( “{0,-35}{1,-9}{2}
“,”Operation”, “Buffer”, “Occupied Count” );
shared.DisplayState( “Initial state” );

Producer producer = new Producer( shared, random );
Consumer consumer = new Consumer( shared, random );

Thread producerThread = new Thread( new ThreadStart( producer.Produce ) );
producerThread.Name = “Producer”;

Thread consumerThread = new Thread( new ThreadStart( consumer.Consume ) );
consumerThread.Name = “Consumer”;

producerThread.Start();
consumerThread.Start();
}
}

public class Consumer
{
private SynchronizedBuffer sharedLocation;
private Random randomSleepTime;

public Consumer( SynchronizedBuffer shared, Random random )
{
sharedLocation = shared;
randomSleepTime = random;
}

public void Consume()
{
int sum = 0;

for ( int count = 1; count <= 10; count++ ) { Thread.Sleep( randomSleepTime.Next( 1, 1001 ) ); sum += sharedLocation.Buffer; } Console.WriteLine("{0} read values totaling: {1}. Terminating {0}.",Thread.CurrentThread.Name, sum ); } } public class Producer { private SynchronizedBuffer sharedLocation; private Random randomSleepTime; public Producer( SynchronizedBuffer shared, Random random ) { sharedLocation = shared; randomSleepTime = random; } public void Produce() { for ( int count = 1; count <= 10; count++ ) { Thread.Sleep( randomSleepTime.Next( 1, 1001 ) ); sharedLocation.Buffer = count; } Console.WriteLine( "{0} done producing. Terminating {0}.",Thread.CurrentThread.Name ); } } [/csharp]

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 &amp;&amp; 
             mt2.thrd.IsAlive &amp;&amp; 
             mt3.thrd.IsAlive); 
 
    Console.WriteLine("Main thread ending."); 
  } 
}