เราลองมาดูโปรแกรมแรกกันครับ โปรแกรมนี้ น่าจะเป็นโปรแกรมพื้นฐานที่สุดสำหรับการทำ Multi-thread เรามาดู code กันเลยดีกว่า
|
simplethread.cs |
using System; using System.Threading; class Class1
{
public void r1()
{
for (int i=0; i<10; i++) {
Console.WriteLine(i);
Thread.Sleep(10);
}
}
public void r2()
{
for (int i=1000; i<1010; i++) {
Console.WriteLine(i);
Thread.Sleep(10);
}
}
}
class Start
{
public static void Main()
{
Class1 class1 = new Class1();
Thread t1 = new Thread(new ThreadStart(class1.r1));
Thread t2 = new Thread(new ThreadStart(class1.r2));
t1.Start();
t2.Start();
Console.ReadLine();
}
}
|
class1 นั้นไม่มีอะไรมากครับ เป็น class ที่มี 2 methods r1, r2 แต่ละ method จะมี for loop เพื่อพิมพ์ค่าตัวเลข 10 ค่าออกไปที่จอภาพ แต่ต่างกันนิดเดียวตรงที่ method r1() พิมพ์ค่าตั้งแต่ 0 - 9 และ method r2() พิมพ์ค่าตั้งแต่ 1000 ถึง 1009
คราวนี้เรามาดูในฟังก์ชัน Main() กัน
Class1 class1 = new Class1(); Thread t1 = new Thread(new ThreadStart(class1.r1)); Thread t2 = new Thread(new ThreadStart(class1.r2)); |
คำสั่้งแรกก็สร้าง object ครับ ส่วนบรรทัดที่ 2 เป็นการสร้าง thread ใหม่ครับ ที่ชื่อว่า t1 โดยที่ thread t1 จะเริ่มต้นที่บรรทัดแรกของ method class1.r1() ส่วนคำสั่งที่ 3 ก็เช่นกัน เราสร้าง thread ที่ชื่อว่า t2 เริ่มต้นบรรทัดแรกของ method class1.r2()
คำสั่งที่สร้าง thread นี้ ใช้ delegate ครับ แต่ผมคงไม่แจงรายละเอียด คุณสามารถดูได้จาก Online Help เรามาดู เรื่อง Thread กันดีกว่า คำสั่งข้างบนนั้น สร้าง Thread เพิ่มขึ้นอีก 2 ตัว รวมกับ thread หลักแล้ว process นี้ก็จะมี thread ทั้งหมด 3 ตัว
แต่ thread ใหม่ทั้ง 2 ตัวยังไม่เริ่มทำงาน จนกว่าคุณเรียก Method Start() ครับ เรามาดูบรรทัดต่อไปกัน
t1.Start(); t2.Start(); |
thread ทั้ง 2 เริ่มทำงานครับ การทำงานจะทำโดยอิสระ ดังนั้นเราจึงเห็นผลลัพธ์ ดังนี้ครับ
|
DOS Prompt |
| C:\CS>simplethread 0 1000 1 1001 2 1002 3 1003 4 1004 5 1005 6 1006 7 1007 8 1008 9 1009 C:\CS>_ |
คงพอมองเห็นภาพของ Multi-thread นะครับ