Reputation: 161
How can I keep a thread alive until certain events happen? I have a client thread that's waiting for a message from the server that will raise an event on the client(I cannot change this behavior). There are multiple such clients waiting for the MessageReceived event. There should be as little latency as possible so putting the threads to sleep for some amount of time is not a good option.
Currently the only option I've come up with is to keep the thread busy in a while loop so that they are active when the event fires. Is there any better option?
Upvotes: 0
Views: 2114
Reputation: 1300
Don't know how much it would help,
What I did to deal with multithreading in an exercise I once had,
It was more of a solution to sync between threads, but I guess it can also fit.
I used a mutex, and In the function called by the thread I added a WaitOne() (I think it's called that way),
and once I wanted the thread to go, I unlocked the mutex.
You can do the same, and maybe when the event is raised, unlock the mutex lock.
Edit: What the answer above me says is true. Mixed things above, it IS a ManualResetEvent not a mutex.
But you can use the method I wrote too, just switch mutex with ManualResetEvent.
Upvotes: 0
Reputation: 4418
Use a ManualResetEvent
. You can create this object, and then use WaitOne()
and then from another thread, call Set()
to release the previous blocking call.
Example:
ManualResetEvent mre = new ManualResetEvent();
public void OnOneThread()
{
//Block here until "OnAnotherThread" is done
mre.WaitOne();
}
public void OnAnotherThread()
{
DoWork();
//Release the other thread
mre.Set();
}
Upvotes: 3