-
StackOverflow 文件
-
C# Language 教程
-
執行緒
-
簡單的完整執行緒演示
class Program
{
static void Main(string[] args)
{
// Create 2 thread objects. We're using delegates because we need to pass
// parameters to the threads.
var thread1 = new Thread(new ThreadStart(() => PerformAction(1)));
var thread2 = new Thread(new ThreadStart(() => PerformAction(2)));
// Start the threads running
thread1.Start();
// NB: as soon as the above line kicks off the thread, the next line starts;
// even if thread1 is still processing.
thread2.Start();
// Wait for thread1 to complete before continuing
thread1.Join();
// Wait for thread2 to complete before continuing
thread2.Join();
Console.WriteLine("Done");
Console.ReadKey();
}
// Simple method to help demonstrate the threads running in parallel.
static void PerformAction(int id)
{
var rnd = new Random(id);
for (int i = 0; i < 100; i++)
{
Console.WriteLine("Thread: {0}: {1}", id, i);
Thread.Sleep(rnd.Next(0, 1000));
}
}
}