C# 一个线程完成并挂起其他线程时的多线程
我想在C# 一个线程完成并挂起其他线程时的多线程,c#,multithreading,C#,Multithreading,我想在islem完成时执行。其他线程挂起,但不工作 我读过关于ManualResetEvent的书,但我无法理解多线程示例。它们只适用于一个简单的线程。另外,我读了这篇文章后发现了类似的问题,比如我正在处理多线程对象如果您只需要取消工作线程,最简单的方法是使用标志。您必须标记标志volatile,以确保所有线程使用相同的副本 islem = new Thread(new ThreadStart(ilk)); islem2 = new Thread(new ThreadStart
islem
完成时执行。其他线程挂起,但不工作
我读过关于
ManualResetEvent
的书,但我无法理解多线程示例。它们只适用于一个简单的线程。另外,我读了这篇文章后发现了类似的问题,比如我正在处理多线程对象如果您只需要取消工作线程,最简单的方法是使用标志。您必须标记标志volatile
,以确保所有线程使用相同的副本
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();
}
如果您确实想暂停(我不知道为什么),可以使用ManualResetEvent。这允许在不消耗暂停线程资源的情况下执行阻塞行为
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.
}
您还可以结合使用这些方法,例如,如果您希望能够暂停线程,执行更多工作,然后取消它们:
//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
}
}