This is simple multi-threading program that draws circles and rectangles. Each shape is handle by individual thread that created every time you press start button. Using sleep method on each thread we can change the speed of each shape.
I have used to implement this program. Double click on Thread_Example.Zip and extract all the files and folders to a folder in C drive.

其中,基类Shapes.cs:
代码如下:
继承Shapes的2个继承类:Rectangle和Circle类定义如下:

using System;

using System.Drawing;

using System.Threading;




namespace ThreadTester



{

public class Rectangle : Shapes


{

public Rectangle(int x,int y,int w,int h, Color c,Form1 f,int spd)


{ xVal = x; yVal = y; color = c; width = w; height = h; frm1 = f; speed = spd;}

public override void paint(Graphics g)


{

try


{

Thread.Sleep(speed);

g.DrawRectangle(new System.Drawing.Pen(frm1.BackColor),xVal,yVal,width,height);

lock(typeof(Thread))


{

xVal = xVal+ base.directionX;

yVal = yVal+ base.directionY;

base.CheckCoordinates();

}

g.DrawRectangle(new System.Drawing.Pen(color),xVal,yVal,width,height);

}

catch


{}

}

}

}



和


using System;

using System.Drawing;

using System.Threading;




namespace ThreadTester



{

public class Circle : Shapes


{

public Circle(int x,int y,int w,int h, Color c, Form1 f, int spd)


{ xVal = x; yVal = y; color = c; width = w; height = h; frm1 = f; speed = spd;}


public override void paint(Graphics g)


{

try


{

Thread.Sleep(speed);

g.DrawEllipse(new System.Drawing.Pen(frm1.BackColor),xVal,yVal,width,height);

lock(typeof(Thread))


{

xVal = xVal+ base.directionX;

yVal = yVal+ base.directionY;

base.CheckCoordinates();

}

g.DrawEllipse(new System.Drawing.Pen(color),xVal,yVal,width,height);

}

catch


{ }

}

}

}



主界面如下:

全局变量定义如下:

public volatile Panel panel1;

public static Color shapeColor = Color.Blue;

public ColorDialog c;

public static int threadCount = 0;

private Hashtable threadHolder = new Hashtable();

private const int shapSize = 15;

private volatile Graphics g;
注意其中的:

private volatile Graphics g;

public volatile Panel panel1;
退出部分代码如下:
选择颜色代码:
开始按钮代码 如下:
当中对线程的定义部分如下:

private void StartThread()


{


/**//* Create the shape object */

Shapes shapes;

if(comboBox1.Text.Equals("Rectangle"))

shapes = new Rectangle(0,0,shapSize,shapSize,shapeColor,this,Convert.ToInt32(comboBoxSpeed.Text.Trim()));

else if(comboBox1.Text.Equals("Circle"))

shapes = new Circle(0,0,shapSize,shapSize,shapeColor,this,Convert.ToInt32(comboBoxSpeed.Text.Trim()));


/**//**The line below is not necessary , but if you want to add more shapes this will help*/

else

shapes = new Rectangle(0,0,shapSize,shapSize,shapeColor,this,Convert.ToInt32(comboBoxSpeed.Text.Trim()));

while(true)


{

try


{ shapes.paint(g); }

catch(Exception e1)


{

Console.WriteLine("Exception in Form1 whileloop >> "+e1);

break;

}

}

}