Multithreading

  • Thread starter Thread starter Tomaz Koritnik
  • Start date Start date
T

Tomaz Koritnik

Hi

I want to synchronize two threads. One thread is doing some time-expensive
calculation and when it needs aditional data for calculation, it has to
acquire data from data object. The problem is that methods in data object
must execute in main thread. Because of this, I can't use Lock() or
Monitor.Enter because code would execute inside calculate thread. In Win32
messages where used for this and my question is what would be the equivalent
in .NET?

In Win32 I would do this:
Calc thread would request for data by posting a message to main thread. Main
thread would gather data (while calc thread is waiting) and then send data
back by posting a message to calc thread. Calc thread would then continue
calculation.

How do I do it in .NET?

regards
Tomaz
 
Hi,

Here is a possible solution.

in your worker thread you call wincontrol.Invoke( getdatamethod) , where
wincontrol is a win control from the main thread, it does not matter which
one, you just want to make sure it does execute in the "main" thread.
Then you could suspend the thread , after the calculation is done the main
thread is responsible for Resume the suspended thread. You have to check
though that the worker thread is suspend , just in case the calculation was
finished before the worker thread entered in Suspend mode.

In any case you will need a lock around the data itself.


cheers,
 
Thanks. This may indeed work and I will try it. One questine though, When I
call Invoke from worker thread, does Invoke wait until method that I specify
finish it's work in the main thread (synchronized)?

regards
Tomaz
 
Hi,

Tomaz Koritnik said:
Thanks. This may indeed work and I will try it. One questine though, When
I call Invoke from worker thread, does Invoke wait until method that I
specify finish it's work in the main thread (synchronized)?


The worker thread will continue to execute.

cheers,
 
Tomaz Koritnik said:
Thanks. This may indeed work and I will try it. One questine though, When
I call Invoke from worker thread, does Invoke wait until method that I
specify finish it's work in the main thread (synchronized)?

regards
Tomaz

Control.Invoke is synchronous, so the caller blocks for the called method to
return.
Control.BeginInvoke is the asynchronous version, which doesn't wait.

Willy.
 
Hi Willy,

You are right :)


cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top