A thread should not star开发者_StackOverflowt event the start method is called.. is it possible? in c#
As this code demonstrates, the thread automatically is created in a suspended state and will not start until you call start.
class Program
{
static void Main(string[] args)
{
Worker w = new Worker();
Console.ReadKey();
w.Start();
Console.ReadKey();
w.Stop();
Console.ReadKey();
}
}
class Worker
{
System.Threading.Thread workerThread;
bool work;
public Worker()
{
System.Threading.ThreadStart ts = new System.Threading.ThreadStart(DoWork);
workerThread = new System.Threading.Thread(ts);
}
public void Start()
{
work = true;
workerThread.Start();
}
public void Stop()
{
work = false;
}
private void DoWork()
{
while(work)
{
Console.WriteLine(System.DateTime.Now.ToLongTimeString());
System.Threading.Thread.Sleep(1000);
}
}
}
(This was created with C# on .NET 3.5, was threading different for 2.0?)
精彩评论