简体   繁体   中英

C# Thread Synchronization

I have a problem with C# threads.

  1. I have eendless process “worker”, which do some and after iteration sleep 3 seconds.

  2. I have a timer function that runs at a given time.

I need the "timer function" do something, then wait for the end "worker" iteration and then pause "worker" until "timer function" is done own task , after that timer function starts a "worker" again.

How can I do that? Best regards Paul

You could use wait handles to control the methods - something like:

private AutoResetEvent mWorkerHandle = new AutoResetEvent(initialState: false);
private AutoResetEvent mTimerHandle = new AutoResetEvent(initialState: false);

// ... Inside method that initializes the threads
{
    Thread workerThread = new Thread(new ThreadStart(Worker_DoWork));
    Thread timerThread = new Thread(new ThreadStart(Timer_DoWork));

    workerThread.Start();
    timerThread.Start();

    // Signal the timer to execute
    mTimerHandle.Set();
}

// ... Example thread methods
private void Worker_DoWork()
{
    while (true)
    {
        // Wait until we are signalled
        mWorkerHandle.WaitOne();

        // ... Perform execution ...    

        // Signal the timer
        mTimerHandle.Set();
    }
}

private void Timer_DoWork()
{
    // Signal the worker to do something
    mWorkerHandle.Set();

    // Wait until we get signalled
    mTimerHandle.WaitOne();

    // ... Work has finished, do something ...
}

This should give you an idea of how to control methods running on other threads by way of a WaitHandle (in this case, an AutoResetEvent ).

You can use a lock to pause a thread while another is doing something:

readonly object gate = new object();

void Timer()
{
    // do something
    ...

    // wait for the end "worker" iteration and then
    // pause "worker" until "timer function" is done
    lock (gate)
    {
        // do something more
        ...
    }
    // start the "worker" again
}

void Worker()
{
    while (true)
    {
        lock (gate)
        {
            // do something
            ...
        }

        Thread.Sleep(3000);
    }
}

Do you need paralel work of Worker and another operation? If not, You can do somthing similar:

EventWaitHandle processAnotherOperationOnNextIteration = new EventWaitHandle(false, EventResetMode.ManualReset);

Worker() 
{
   while(true)
   {
       doLongOperation();
       if (processAnotherOperationOnNextIteration.WaitOne(0))
       {
           processAnotherOperationOnNextIteration.Reset();
           doAnotherOperation();
       }
       Thread.Sleep(3000);
   }
}

in timer

 void Timer()
 {
    processAnotherOperationOnNextIteration.Set();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM