这是三个线程的正常使用吗? 我可以使用一个线程作为GUI表单,一个用于计算,最后一个作为主人来杀死其他人吗?
这里我开始我的三个线程,当我按下ESC键时它会终止所有进程。这是一种正常的做法,还是更精心的做法?
namespace ThreadingTest
{
class Program
{
static void Main(string[] args)
{
bool exit = false;
System.Threading.Thread myThread;
System.Threading.Thread mysecondthread;
System.Threading.Thread Killingthread;
myThread = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadLoop));
mysecondthread = new System.Threading.Thread(new System.Threading.ThreadStart(SecondThreadwork));
Killingthread = new System.Threading.Thread(new System.Threading.ThreadStart(KillProcess));
myThread.Start();
mysecondthread.Start();
Killingthread.Start();
while (exit == false)
{
var FirstThreadState = myThread.ThreadState;
var SecondThreadState = mysecondthread.ThreadState;
var ThirdThreadState = Killingthread.ThreadState;
Console.WriteLine(ThirdThreadState.ToString());
if (ThirdThreadState == System.Threading.ThreadState.Stopped) exit = true;
System.Threading.Thread.Sleep(500);
}
myThread.Abort();
Console.WriteLine("first thread ended.");
mysecondthread.Abort();
Console.WriteLine("second thread ended.");
Killingthread.Abort();
Console.WriteLine("third thread ended.");
}
public static void ThreadLoop()
{
while (System.Threading.Thread.CurrentThread.IsAlive)
{
System.Threading.Thread.Sleep(500);
Console.WriteLine("I'm working...");
}
}
public static void SecondThreadwork()
{
while (System.Threading.Thread.CurrentThread.IsAlive)
{
System.Threading.Thread.Sleep(500);
Console.WriteLine("me too...");
}
}
public static void KillProcess()
{
do {
while (!Console.KeyAvailable)
{
System.Threading.Thread.Sleep(500);
Console.WriteLine("third ON."); // Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
}
}
谢谢