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

โปรแกรม C# ใช้ Sleep Method ของ Thread

เมธอด Thread.Sleep() ใช้หยุดเธรดชั่วคราวเป็นเวลาที่กำหนด (มิลลิวินาที)

int sleepfor = 2000; // 2 วินาที
Thread.Sleep(sleepfor);

ตัวอย่างโค้ดเต็ม

using System;
using System.Threading;
namespace MyApplication {
    class ThreadCreationProgram {
        public static void CallToChildThread() {
            Console.WriteLine("Child thread starts");
            int sleepfor = 2000;
            Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000);
            Thread.Sleep(sleepfor);
            Console.WriteLine("Child thread resumes");
        }
        static void Main(string[] args) {
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Console.WriteLine("In Main: Creating the Child thread");
            Thread childThread = new Thread(childref);
            childThread.Start();
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 2 seconds
Child thread resumes

คำอธิบาย: เธรดหลักสร้างเธรดลูก ให้เธรดลูกทำงาน พิมพ์ข้อความ หยุด 2 วินาที แล้วทำงานต่อ ในขณะเดียวกันเธรดหลักรอด้วย Console.ReadKey()