Unity线程开启和终止

thread = new Thread(new ThreadStart(不带括号的函数名));

var thread = new Thread(
new ThreadStart(
() =>
{
while (true)
{
//该线程会进行无限循环,自己不会结束
Thread.Sleep(100);
}
}));

thread.IsBackground = true;
thread.Start();//启动线程

thread.Abort();//调用Thread.Abort方法试图强制终止thread线程

//上面调用Thread.Abort方法后线程thread不一定马上就被终止了,所以我们在这里写了个循环来做检查,看线程thread是否已经真正停止。其实也可以在这里使用Thread.Join方法来等待线程thread终止,Thread.Join方法做的事情和我们在这里写的循环效果是一样的,都是阻塞主线程直到thread线程终止为止
while (thread.ThreadState!=ThreadState.Aborted)
{
//当调用Abort方法后,如果thread线程的状态不为Aborted,主线程就一直在这里做循环,直到thread线程的状态变为Aborted为止
Thread.Sleep(100);
}

猜你喜欢

转载自blog.csdn.net/weixin_43780907/article/details/130112853