Handling COM Callbacks in C# Client

Go To StackoverFlow.com


Here is how the application is designed - I have a COM server raising events on certain conditions. I have a C# client UI which is supposed to handle these events raised by this COM server.

There is a delegate in my C# client which I pass to the COM server and it calls back on an event. I have a custom wrapper which marshals the delegate as function pointer. Like so...

     Fxn1inCOMWrapper([In, MarshalAs(UnmanagedType.FunctionPtr)] Client.SetStatusDelegate StatusCallback);

The callback mechanism works. The problem here is that once I get the callback, I am supposed to call another method in the COM Server to invoke further processing.

I am not able to make the second function call to COM component from the C# callback method, and it corrupts the stack in COM and it returns me an exception. I am guessing it is the case because the callback is not the same thread on which the COM object was created and the first call was made. Is it possible to work around this problem?

One option was to set a flag in event callback in C# client. And on a timer from the main thread, check for the flag and if yes, make the second call. But there surely has to be a more elegant way of doing this...Can anyone help please?

2012-04-04 00:21
by DeepthiU
It doesn't have anything to do with threading, the attribute doesn't do anything. You'll need to give a better diagnostic of exactly what goes wrong. COM supports events, you might want to use them - Hans Passant 2012-04-04 04:54


Try changing the threading attribute on your Main() function. For example, if you have:

static void Main()

change it to:

static void Main()
2012-04-04 00:42
by Jim Rhodes