示例
Program.cs
namespace ThreadingApp
{
internal class Program
{
static void Main(string[] args)
{
Thread mainThread = Thread.CurrentThread;
mainThread.Name = "Main thread";
Console.WriteLine(mainThread.Name + " Started"); //Main thread
NumbersCounter numbersCounter = new NumbersCounter();
ParameterizedThreadStart ts1 = new ParameterizedThreadStart(numbersCounter.CountUp);
Thread t1 = new Thread(ts1) { Name = "CountUp Thread", Priority = ThreadPriority.Highest };
t1.Start(100);
Console.WriteLine($"{t1.Name}({t1.ManagedThreadId}) is {t1.ThreadState.ToString()}");
ParameterizedThreadStart ts2 = new ParameterizedThreadStart(numbersCounter.CountDown);
Thread t2 = new Thread(ts2) { Name = "CountDown Thread", Priority = ThreadPriority.Lowest };
t2.Start(100);
Console.WriteLine($"{t2.Name}({t2.ManagedThreadId}) is {t2.ThreadState.ToString()}");
//mainThread waiting for t1 and t2 completed
t1.Join();
t2.Join();
Console.WriteLine(mainThread.Name + " Completed");
Console.ReadKey();
}
}
class NumbersCounter
{
public void CountUp(object? count)
{
try
{
Console.WriteLine("CountUp Started");
Thread.Sleep(1000);
int? countInt= (int?)count;
for (int? i = 1; i <= countInt; i++)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write($"i = {i}, ");
Thread.Sleep(100);
}
Thread.Sleep(1000);
Console.WriteLine("CountUp Completed");
}
catch (ThreadInterruptedException ex)
{
Console.WriteLine("CountUp Thread interrupted: " + ex.ToString());
}
}
public void CountDown(object? count)
{
try
{
Console.WriteLine("CountDown Started");
Thread.Sleep(1000);
int? countInt = (int?)count;
for (int? j = countInt; j >= 1; j--)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write($"j = {j}, ");
Thread.Sleep(100);
}
Thread.Sleep(1000);
Console.WriteLine("CountDown Completed");
}
catch (ThreadInterruptedException ex)
{
Console.WriteLine("CountDown Thread interrupted: " + ex.ToString());
}
}
}
}