创建线程时,需要指定线程入口,即通过ThreadStart指定线程要去执行的“函数”或者“过程”。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Demo
{
public class ThreadClass
{
public void ThreadFunction()
{
Console.WriteLine("Thread function is running...");
}
}
class Program
{
static void Main(string[] args)
{
ThreadClass aThreadClass = new ThreadClass();
Thread aThread = new Thread(new ThreadStart(aThreadClass.ThreadFunction));
aThread.Start();
// When it is main thread, just sleep for some time.
while (!aThread.IsAlive)
{
Thread.Sleep(3000);
}
Console.ReadLine();
aThread.Abort();
aThread.Join();
Console.WriteLine("Thread function has been aborted!");
try
{
// Try to restart the aborted thread
aThread.Start();
}
catch (ThreadStateException ex)
{
Console.WriteLine("Error: " + ex.ToString());
}
Console.ReadLine();
}
}
}