Reputation: 103
I have a problem with C# threads.
I have eendless process “worker”, which do some and after iteration sleep 3 seconds.
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
Upvotes: 2
Views: 1659
Reputation: 8623
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).
Upvotes: 3
Reputation: 2880
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();
}
Upvotes: 0
Reputation: 217401
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);
}
}
Upvotes: 1