[英]Best way to wait for a background thread to finish processing in C#
我有一个后台主题。 如果后台线程忙,我想等待它完成其工作,然后继续下一个请求。 我已通过以下方式实现它。 Process是后台线程的名称。
if (process.IsBusy)
{
do
{
isProcessBusy = process.IsBusy;
} while (isProcessBusy == false);
SetIsDirty(status, GetContext());
}
else
{
SetIsDirty(status, GetContext());
}
这是最好的方式还是有其他方法来实现这种逻辑?
Thread
类有一个名为Join
的方法,它阻塞直到调用它的线程退出。
看看这里 。
根本不建议这样做。 通过这种方式,您可以始终在不使用任何实际工作的情况下使用CPU。
如果要使用相同的方法,请在检查线程是否处于活动状态之前使用一些等待句柄或睡眠。
不过,我会建议您检查此文章为获得在后台线程和不同的同步方式更好的理解。
要么
您还可以考虑使用ThreadPool
来处理后台任务。 以下是微软的一个例子 。
您可以使用AutoResetEvent
:
AutoResetEvent resetEvent = new AutoResetEvent(false);
private void StartProcess()
{
new Thread(DoProcess).Start();
}
private void DoProcess()
{
List<String> list = new List<String>() {
"Value 1",
"Value 2",
"Value 3",
"Value 4",
"Value 5",
};
foreach (String item in list)
{
process.RunWorkerAsync(item);
if (!resetEvent.WaitOne())
{
// Some exception
break;
}
resetEvent.Reset();
}
}
private void process_DoWork(object sender, DoWorkEventArgs e)
{
Debug.WriteLine(e.Argument.ToString());
Thread.Sleep(1000);
}
private void process_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
resetEvent.Set();
}
是否要等到某个任务完成后,使用Thread.Sleep(0)或Thread.Sleep(100)来避免烧掉100%的CPU内核只是为了等待一个标志被引发。
有一些事件和信号量的方法,但这个方法很简单,不会有点伤害。
阻塞一个线程,等待另一个线程结束的方法称为锁定。 C#允许我们使用Monitor类或lock {}构造来锁定代码。 看看这个。
举个例子:
Class1()
{
// construct two threads for our demonstration;
Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
Thread thread2 = new Thread(new ThreadStart(DisplayThread2));
// start them
thread1.Start();
thread2.Start();
}
void DisplayThread1()
{
while (_stopThreads == false)
{
// lock on the current instance of the class for thread #1
lock (this)
{
Console.WriteLine("Display Thread 1");
_threadOutput = "Hello Thread1";
Thread.Sleep(1000); // simulate a lot of processing
// tell the user what thread we are in thread #1
Console.WriteLine("Thread 1 Output --> {0}", _threadOutput);
} // lock released for thread #1 here
}
}
void DisplayThread2()
{
while (_stopThreads == false)
{
// lock on the current instance of the class for thread #2
lock (this)
{
Console.WriteLine("Display Thread 2");
_threadOutput = "Hello Thread2";
Thread.Sleep(1000); // simulate a lot of processing
// tell the user what thread we are in thread #1
Console.WriteLine("Thread 2 Output --> {0}", _threadOutput);
} // lock released for thread #2 here
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.