islem = new Thread(new ThreadStart(ilk));
islem2 = new Thread(new ThreadStart(ikinci));
islem3 = new Thread(new ThreadStart(ucuncu));
islem4 = new Thread(new ThreadStart(dorduncu));
islem.Start();
islem2.Start();
islem3.Start();
islem4.Start();
if (!islem.IsAlive)
{
islem2.Suspend();
islem3.Suspend();
islem4.Suspend();
}
我想在islem
完成时做。其他线程暂停,但它不起作用
我读到了ManualResetEvent
,但我无法弄清楚多线程的例子。他们只使用一个简单的线程。此外,我还阅读了http://www.albahari.com/threading/part4.aspx#_Suspending_and_Resuming本文,并查看了类似C# controlling threads (resume/suspend) How to pause/suspend a thread then continue it? Pause/Resume thread whith AutoResetEvent的类似问题我正在使用多线程对象
答案 0 :(得分:1)
如果您只需要取消工作线程,最简单的方法是使用标志。您必须标记标志volatile
以确保所有线程都使用相同的副本。
private volatile bool _done = false;
void Main()
{
StartWorkerThreads();
}
void WorkerThread()
{
while (true)
{
if (_done) return; //Someone else solved the problem, so exit.
ContinueSolvingTheProblem();
}
_done = true; //Tell everyone else to stop working.
}
如果你真的想暂停(我不确定为什么)你可以使用ManualResetEvent。这允许阻塞行为而不消耗暂停线程的资源。
//When signalled, indicates threads can proceed.
//When reset, threads should pause as soon as possible.
//Constructor argument = true so it is set by default
private ManualResetEvent _go = new ManualResetEvent(true);
void Main()
{
StartWorkerThreads();
}
void WorkerThread()
{
while (true)
{
_go.WaitOne(); //Pause if the go event has been reset
ContinueSolvingTheProblem();
}
_go.Reset(); //Reset the go event in order to pause the other threads
}
您还可以合并这些方法,例如:如果你想能够暂停线程,做更多的工作,然后取消它们:
private volatile bool _done = false;
private ManualResetEvent _go = new ManualResetEvent(true);
void Main()
{
StartWorkerThreads();
}
void WorkerThread()
{
while (true)
{
if (_done) return; //Exit if problem has been solved
_go.WaitOne(); //Pause if the go event has been reset
if (_done) return; //Exit if problem was solved while we were waiting
ContinueSolvingTheProblem();
}
_go.Reset(); //Reset the go event in order to pause the other threads
if (VerifyAnswer())
{
_done = true; //Set the done flag to indicate all threads should exit
}
else
{
_go.Set(); //Tell other threads to continue
}
}