Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Join, Sleep และ Abort ในการทำงานแบบมัลติเธรด C#

Join

บล็อกเธรดที่เรียกจนกว่าเธรดเป้าหมายจะสิ้นสุด การทำงาน รองรับ Overload หลายรูปแบบ (ระบุ Timeout, CancellationToken)

Sleep

หยุดเธรดปัจจุบันชั่วคราวตามระยะเวลาที่ระบุ (มิลลิวินาที หรือ TimeSpan)

Abort

ยกเลิกเธรด (Thread Abort) - ไม่แนะนำให้ใช้ใน .NET Core/.NET 5+ เพราะอาจทำให้สถานะโปรแกรมไม่เสถียร ควรใช้ CancellationToken แทน

ตัวอย่าง Join

using System;
using System.Threading;

namespace Sample
{
    class Demo
    {
        static void Run()
        {
            for (int i = 0; i < 2; i++)
                Console.Write("Sample text!");
        }

        static void Main(string[] args)
        {
            Thread t = new Thread(Run);
            t.Start();
            t.Join(); // รอจนกว่า t จะจบ
            Console.WriteLine("Thread terminated!");
        }
    }
}

ตัวอย่าง Sleep และ Abort (รูปแบบเก่า)

using System;
using System.Threading;

namespace Demo
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread()
        {
            try
            {
                Console.WriteLine("Child thread starts");
                for (int counter = 0; counter <= 10; counter++)
                {
                    Thread.Sleep(500); // หยุด 500 ms
                    Console.WriteLine(counter);
                }
                Console.WriteLine("Child Thread Completed");
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine("Thread Abort Exception");
            }
            finally
            {
                Console.WriteLine("Couldn't catch the Thread Exception");
            }
        }

        static void Main(string[] args)
        {
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Thread childThread = new Thread(childref);
            childThread.Start();
            Thread.Sleep(2000); // หยุด Main 2 วินาที
            Console.WriteLine("In Main: Aborting the Child thread");
            childThread.Abort(); // ยกเลิก Child Thread
        }
    }
}

แนวทางปัจจุบัน: ใช้ CancellationToken และ Task แทน Thread โดยตรง เพื่อการจัดการการยกเลิกที่ปลอดภัยกว่า