我的C++ GUI应用程序(Visual Studio)中的事件中有两个线程。该函数必须运行一些代码,但是我想在经过指定时间后结束线程。我创建的线程是:
ThreadStart^ oThread = gcnew ThreadStart(this, &MyForm::ThreadMethod);
Thread^ newThread = gcnew Thread(oThread);
newThread->Start();
如何结束线程?因为我尝试的结果以异常结尾。
最佳答案
如果没有什么可以阻止MyForm::ThreadMethod
跟踪自己花费的时间,那么为什么不将计时集成到您的线程化工作中呢?
void ThreadMethod
{
Int64 watchdog = 1000L * 5L * 60L; // 5 minutes
System::Diagnostics::Stopwatch^ sw
= System::Diagnostics::Stopwatch::StartNew();
while (sw->ElapsedMilliseconds < watchdog
&& otherCondition)
{
// do your work here
}
}
关于.net - 未完成的结束线程^,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18744086/