0

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?

Sid M
  • 4,354
  • 4
  • 30
  • 50
Mark Segal
  • 5,427
  • 4
  • 31
  • 69
  • 2
    Look at [AutoResetEvent](http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent%28v=vs.110%29.aspx). It's made for this sort of thing, there are examples at MSDN as well. – Candide Jul 17 '14 at 07:12
  • How about a [`Mutex`](http://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx)? – M. Mimpen Jul 17 '14 at 07:13
  • 1
    You can get the answer at http://stackoverflow.com/questions/1584062/how-to-wait-for-thread-to-finish-with-net – lokendra jayaswal Jul 17 '14 at 07:14
  • http://stackoverflow.com/questions/1784928/c-sharp-four-patterns-in-asynchronous-execution – smali Jul 17 '14 at 07:19

2 Answers2

3

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/

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
1

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);
}
Udontknow
  • 1,472
  • 12
  • 32