views:

573

answers:

2

I have inherited some majorly spaghetti code (combination C#/VB) that I'm trying to understand here.

This appears to be a really weird situation where there are two successive calls to fire events to a remote object, which is being done by calling the DynamicInvoke method of a delegate, of the form:

delegate1.DynamicInvoke(args1);
// some code here
delegate2.DynamicInvoke(args2);

delegate1 and delegate2 both refer to methods in the same remote "subscriber" object.

According to everything I can read in the documentation, DynamicInvoke looks like it should be synchronous. But I can see, before my eyes, when I put breakpoints into the remote process, that the methods referred to by delegate1 and delegate2 are running simultaneously, in different threads.

Is this another Microsoft "undocumented feature"? Should I have expected this? Any explanations as to why this should be? And if it's meant to run asynchronously, how can DynamicInvoke have a return value?

Thanks! Shaul

+2  A: 

DynamicInvoke is definately a synchronous operation. The problem though is that the delegate it points to make not be synchronous. For instance the following code will call Console.WriteLine() in an asynchronous fashion.

Action write = () => Console.WriteLine("foo");
Action del1 = () => { ThreadPool.QueueUserWorkItem(write); }
...
del1.DynamicInvoke();

del1 will be executed synchronously but it will create an asynchronous work item.

I would look for the code the delegate is executing and see if they are doing some asyc magic under the hood.

JaredPar
It's a good guess, but no, no threads being called by the delegate. The remote object has two threads, each originating the delegated code itself.
Shaul
A: 

My main advice would be to inspect the call stacks carefully in your two processes.

Is it possible that your "spaghetti" code actually has a callback in it. Your first delegate calls your remote process, it calls back, and your second delegate is being invoked from the nested callback?

morechilli