user1108948
user1108948

Reputation:

Make sure method finishes prior to another method call

I have a windows service that is consumed by several stations. When the service starts, I want to finish my pre_process task than begin my thread.

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

I am not confident my code, I thought that the thread could be starting before pre_process() method. Thanks for your opinion.

Upvotes: 2

Views: 1518

Answers (3)

bas
bas

Reputation: 14902

If you want to be sure if your PreProcess method is done, then use an AutoResetEvent to signal the executing Thread to continue.

    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;
    }

In your PreProcess method you simply end with signalling

    private void PreProcess()
    {
        // Do pre processing stuff

        _resetEvent.Set();
    }

Your ServiceLoop "waits" until your PreProcess method signals to start

    public void ServiceLoop()
    {
        // Guaranteed nothing else will be executed until 
        // the reset event is signalled
        _resetEvent.WaitOne(); 

        while (_running) { /* .. */ }
    } 

Upvotes: 1

Yair Nevet
Yair Nevet

Reputation: 13003

If you have any ambiguity as to the current running threads in your process, you can always test the number of current threads so that you will be able to start your service only when the Main thread is alive without any other spawned running threads:

while(Process.GetCurrentProcess().Threads > 1);
worker.Start();

Upvotes: 1

Nahum
Nahum

Reputation: 7197

is pre_process(); a synchronous operation or asynchronous? you need to make sure that all calls by the pre_process(); method are synchronous. if so the method is also synchronous and it will return only after finishing. if there are asynchronous operations you must wait for those to finish.

Upvotes: 0

Related Questions