Reputation: 5560
I have method A that runs on thread #1.
I also have method B that runs on thread #2.
Method A writes to a shared object a function C (method that receives an object value and returns a Boolean value) that should be executed on some event via method B. (method B is a TCP listener method that runs forever)
I wish that method A will wait until that event occurs AND the C is finished. Currently its implemented with a Sleep based for loop (with timeout and such).
Let me make myself more clear, the flow is like this:
Method B (on thread #2): while(true) { process data, if data has x then someFunc(..) }
Method A (on thread #1): someFunc = (obj) => {...};
wait until someFunc is executed by B & is finished;
do more stuff
Whats the smartest way of achieving this?
Upvotes: 0
Views: 699
Reputation: 73502
Use AutoResetEvent
or ManualResetEvent
private AutoResetEvent signal = new AutoResetEvent(false);
void MethodB()
{
//process data
if(condition)
{
signal.Set();//Say you're finished
}
}
void MethodA()
{
//Do something
signal.WaitOne();//Wait for the signal
//Here do whatever you want. We received signal from MethodB
}
I recommend reading http://www.albahari.com/threading/
Upvotes: 3
Reputation: 1580
Use a lock and the Monitor class.
private object _lock = new object();
...
private void StartTaskAndWait()
{
lock (_lock)
{
new Task(DoSomething).Start();
Monitor.Wait()
}
}
Use Pulse at the end of the task method to "wake up" the waiting thread.
lock (_lock)
{
Monitor.Pulse(_lock);
}
Upvotes: 1