Is GCHandle.Alloc thread safe?

G

Guest

I use a method for threading that instantiates an object that is a wrapper to
a DLL (written in C).

The wrapper class is passed a byte array, and then does

GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr ptr = (IntPtr)(handle.AddrOfPinnedObject().ToInt32() +
buffer.Length-1);

It passes ptr to the DLL function FunctionX().

I've run my application in debug mode, and it errors calling FunctionX()
with more than one thread. A single thread does not cause a problem.

When I check Autos for each of the threads, one thread shows "handle" above
as being correctly allocated, and handle.Target = {System.Array}. The other
thread shows "error: cannot obtain value" for

handle.__InternalTarget
handle.IsAllocated
handle.Target

So is "handle" above thread safe? Is there a better way to do this? Thanks,

JA
 

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