static void Main(string[] args)
{
Thread th = new Thread(new ThreadStart(fun));
th.Start(); //首次启动子线程 Thread.Sleep(3000); //主线程停三秒,等待子线程结束 th.Start(); //再次启动子线程(这个时候子线程已经停了) --这个地方就会出现异常:线程正在运行或被终止;它无法重新启动。
} static void fun()
{
Thread.Sleep(1000); //子线程停一秒
}我想再次用这个线程的句柄th启动线程,怎么实现?
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;namespace ConsoleApplication30
{
class Program
{
delegate void f(); static f F = new f(fun); static void Main(string[] args)
{
IAsyncResult AR = F.BeginInvoke(null, null);
AR.AsyncWaitHandle.WaitOne(3000); //等3秒,不填等于死等
if (AR.IsCompleted) // 超时?
{
AR = F.BeginInvoke(null, null);
AR.AsyncWaitHandle.WaitOne(3000); //等3秒,不填等于死等
if (AR.IsCompleted) // 超时?
Console.WriteLine("ok");
}
Console.Read();
} static void fun()
{
Thread.Sleep(1000); //子线程停一秒
Console.Write(".");
}
}
}
while ((th.ThreadState & (ThreadState.Unstarted | ThreadState.Stopped)) == 0)
{
;//子如果线程没有结束,则继续
}