我有一个由多个站点使用的 Windows 服务。当服务启动时,我想完成我的 pre_process
任务而不是开始我的线程。
public class XML_Processor : ServiceBase
{
Thread worker;
bool running;
public bool Start()
{
pre_process();// add files to queue, please ensure it completes first.
bool success = true;
running = true;
worker = new Thread(new ThreadStart(ServiceLoop));
worker.Start();
return (success);
}
public bool Stop()
{
// blah
}
public void ServiceLoop()
{
string fileName;
while (running)
{
// blah
我对我的代码没有信心,我认为线程可能在 pre_process() 方法之前启动。 感谢您的意见。
最佳答案
如果您想确定您的 PreProcess
方法是否已完成,请使用 AutoResetEvent
向正在执行的线程
发出信号以继续。
private bool _running;
private Thread worker;
private readonly AutoResetEvent _resetEvent = new AutoResetEvent(false);
public bool Start()
{
// Make sure the reset event is in not signalled state
_resetEvent.Reset();
// Do you pre processing
PreProcess();
_running = true;
worker = new Thread(ServiceLoop);
worker.Start();
return _running;
}
在您的 PreProcess
方法中,您只需以信号结束
private void PreProcess()
{
// Do pre processing stuff
_resetEvent.Set();
}
您的ServiceLoop
“等待”,直到您的PreProcess
方法发出启动信号
public void ServiceLoop()
{
// Guaranteed nothing else will be executed until
// the reset event is signalled
_resetEvent.WaitOne();
while (_running) { /* .. */ }
}
关于c# - 确保方法在另一个方法调用之前完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20762400/