0

I have two threads t1 and t2. I get information in t1 and based on it I want to call function in t2 which will work in t2. How can I do it?

Edit:

t2 is thread with c# form. t1 is working in a loop and it gets information that t2 should call function. I think that shared objects won't work, because t2 doesn't work in a loop, so I can't check if some object has changed.

Community
  • 1
  • 1
vesper
  • 155
  • 1
  • 3
  • 9

4 Answers4

2

Share the object between both threads (for example a member of a class where both threads run) and access it using the lock pattern:

object _someobject; // as a member for example

...

lock (_someobject)
{
// manipulate the object
}

This ensures object consistency with avoiding both threads interacting with the shared object at the same time.

Another option would be to use a MethodInvoker if one of the threads is a GUI thread for example.

Community
  • 1
  • 1
jdehaan
  • 19,700
  • 6
  • 57
  • 97
2

I believe the proper way would be to use Invoke or BeginInvoke. You call it on t1, and it gets executed on t2. You need to have a reference to some control running in t2, e.g., the form itself.

You can include the data into the closure, which you invoke in t2.

Vlad
  • 35,022
  • 6
  • 77
  • 199
0

I envision using a volatile variable to store the information found by t1 while t2 loops using an exception until the desired informaiton is found. But I could be wrong.

Chad Harrison
  • 2,836
  • 4
  • 33
  • 50
0

You would use Monitor.Wait and Pulse. They will share a locking object and a signalling variable. The waiting thread would be blocked until signaled (pulsed by working thread). e.g:

    bool _go;
lock (_locker)
            {
                while (!_go) Monitor.Wait(_locker);

            }
            CallFunc();

Working thread:

   // do work here
   DoWork();
   lock (_locker)
        {
            _go = true;
            Monitor.PulseAll(_locker);
        }
dashton
  • 2,684
  • 1
  • 18
  • 15
  • The thread t2 where the function should be executed is a GUI thread. You cannot do long `Wait`s there. – Vlad Jun 07 '11 at 19:30
  • You are correct, but he doesn't say actually say UI thread. I assumed they are a couple of worker threads. Anyway, it is fairly pointless trying to write code to solve a problem, where the problem isn't clear because the OP didn't post any code. Lesson learned. :-| – dashton Jun 08 '11 at 07:44
  • anyway, we are here to help, and in many cases answer requires some guesswork. With guessing, one cannot make a reliable solution. – Vlad Jun 08 '11 at 11:16