日期:2014-05-18  浏览次数:21155 次

C#中如何限定线程的运行时间?
各位高手,在c#中如何取得线程的运行时间,并在线程超过一定时间后终止其运行.希望有帖出代码,谢谢!

------解决方案--------------------
System.Threading.Timer t = new System.Threading.Timer(new System.Threading.TimerCallback(AbortMethod),null,0,5*1000);
------解决方案--------------------

1.加入using System.Threading命名空间;

2.先在类中定义一个成员变量:
Thread t;
System.Threading.Timer time; //线程计时器.

private void Form_Load(object sender, EventArgs e)
{
t=new Thread(new ThreadStart(start));
t.Start();

try
{
//TimerCallback是一个委托类型,第三个参数是开始计时,每四参数是间隔长(以ms为单位).
time = new System.Threading.Timer(new TimerCallback(method), null, 0,2000);

}
catch { }
}

void method(object o) //注意参数.
{
t.Abort(); //终止线程.
if (!t.IsAlive)
{//终止成功.
//终止计时器
time.Change(Timeout.Infinite, Timeout.Infinite);
MessageBox.Show("method");

}
}
void start()
{
MessageBox.Show("start");
}

请多多指教!