示例
Program.cs
namespace ThreadingApp
{
internal class Program
{
static void Main(string[] args)
{
Thread mainThread = Thread.CurrentThread;
mainThread.Name = "Main thread";
Console.WriteLine(mainThread.Name); //Main thread
NumbersCounter numbersCounter = new NumbersCounter();
ThreadStart ts1 = new ThreadStart(numbersCounter.CountUp);
Thread t1 = new Thread(ts1);
t1.Name = "CountUp Thread";
Console.WriteLine($"{t1.Name} is {t1.ThreadState.ToString()}");
t1.Start();
Console.WriteLine($"{t1.Name} is {t1.ThreadState.ToString()}");
ThreadStart ts2 = new ThreadStart(numbersCounter.CountDown);
Thread t2 = new Thread(ts2);
t2.Name = "CountDown Thread";
Console.WriteLine($"{t2.Name} is {t2.ThreadState.ToString()}");
t2.Start();
Console.WriteLine($"{t2.Name} is {t2.ThreadState.ToString()}");
Console.WriteLine(mainThread.Name + " completed");
Console.ReadKey();
}
}
class NumbersCounter
{
public void CountUp()
{
for (int i = 1; i <= 100000; i++)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write($"i = {i}, ");
}
}
public void CountDown()
{
for (int j = 100000; j >=1; j--)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write($"j = {j}, ");
}
}
}
}