Check KeyCode from KeyEventArgs

   



using System;
using System.Drawing;
using System.Windows.Forms;
   
class ExitOnX: Form
{
     public static void Main()
     {
          Application.Run(new ExitOnX());
     }
     public ExitOnX()
     {
          Text = "Exit on X";
     }
     protected override void OnKeyDown(KeyEventArgs kea)
     {
          if (kea.KeyCode == Keys.X)
               Close();
     }
}
           
          


Close Form with Pressing X key

   




using System;
using System.Drawing;
using System.Windows.Forms;
   
class ExitOnX: Form
{
     public static void Main()
     {
          Application.Run(new ExitOnX());
     }
     public ExitOnX()
     {
          Text = "Exit on X";
     }
     protected override void OnKeyDown(KeyEventArgs kea)
     {
          if (kea.KeyCode == Keys.X)
               Close();
     }
}
           
          


Event system explained in detail

   

using System;

namespace Demo
{
    //step 0. use event to simply complex interaction, independent data process module

    //step 1. declare a event signatrue
    public delegate void OnUserDeviceInsertedEvent(object sender, UserDeviceInsertedArgs e);

    //step 2. declare the event args
    public class UserDeviceInsertedArgs : EventArgs
    {
        public string DeviceData;
    }

    //step 3. declare a real work class which has 1 event field member and 1 working method member, in the method event will be triggered when condiation ready

    public class MagCard
    {
        public OnUserDeviceInsertedEvent OnDeviceInserted;
        public void StartingWork()
        {
            UserDeviceInsertedArgs data = new UserDeviceInsertedArgs();
            data.DeviceData = "Demo Data";
            if (OnDeviceInserted != null)
            {
                OnDeviceInserted(this, data);
            }
        }
    }

    //step 4. in main system, ord the event and supperly suitable process
    static class Program
    {
        /// <summary>
        /// ??????????
        /// </summary>
        [STAThread]
        static void Main()
        {
            MagCard machine = new MagCard();
            machine.OnDeviceInserted += new OnUserDeviceInsertedEvent(EventHandler_OnDeviceInserted);
            machine.StartingWork();
            Console.ReadKey();
        }

        private static void EventHandler_OnDeviceInserted(object sender, UserDeviceInsertedArgs e)
        {
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine(e.DeviceData);
            Console.ResetColor();
        }
    }
    //Coding by MoonKite,2010-June,Study C#
    //Thanks for Java2s,I learned a lot form this website.
}       
           
          


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]