Threads and Callback Delegates

S

Steve Lutz

Hi,
I have a simple question that I cannot seem to find the answer to.

Let's say my application has 2 threads, a Main thread and a Worker thread.
As the worker thread progresses, it send results back to the main thread via
a delegate. What thread does the delegate run in?
 
J

Jon Skeet [C# MVP]

Steve Lutz said:
I have a simple question that I cannot seem to find the answer to.

Let's say my application has 2 threads, a Main thread and a Worker thread.
As the worker thread progresses, it send results back to the main thread via
a delegate. What thread does the delegate run in?

How are you invoking the delegate? If you're just calling it directly,
it executes in the same thread you're calling it from. If you call
BeginInvoke on it, it executes on a threadpool thread.
 
J

John Puopolo

Steve,

I have not tried it, but I would assume it would be the Worker (in the
synchronous case). To explicitly marshal calls, you would need an
implementation of ISynchronizeInvoke - which I do not believe
System.Delegate implements. Therefore, the delegrate run in the
context of the thread that calls it. In the async case (if the Worker
calls the Main via BeginInvoke), the CLR uses a thread from the
process thread pool.

You can prove all of this to yourself quite readily by implementing a
quick program whose test methods print out the current thread id.

Hope this helps.

John
 

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

Top