Ngôn ngữ C# - Thread Sleep
Thread Sleep trong C#
Ví dụ sau minh họa cách sử dụng phương thức sleep() để làm một Thread dừng trong một khoảng thời gian cụ thể được tính theo milliseconds.
using System;
using System.Threading;
public class MyThread
{
public void Thread1()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
Thread.Sleep(200);
}
}
}
public class ThreadExample
{
public static void Main()
{
MyThread mt = new MyThread();
Thread t1 = new Thread(new ThreadStart(mt.Thread1));
Thread t2 = new Thread(new ThreadStart(mt.Thread1));
t1.Start();
t2.Start();
}
}
Kết quả:
0
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9