c# - Keep object alive during unmanaged asynchronous operation -
i'm working unmanaged function takes pointer unmanaged memory. function returns when called , asynchronously operates on memory in background. takes additional intptr passes managed code when operation completes. it's possible have multiple such operations running @ same time.
i'm encapsulating pointer unmanaged memory in custom safebuffer instance i'd when asynchronous operation completes. safebuffer ensures memory gets released when there no references it. problem memory, of course, shouldn't released while it's still in use unmanaged function.
how can achieve this? unmanaged function called billions of times, performance critical.
i allocate gchandle whenever call function, use safebuffer when operation completes, , free it. however, allocating handles seems expensive , performance decreases on time.
i allocate gchandle once, unmanaged memory not released when memory not in use unmanaged function , there no references safebuffer.
any ideas?
you keep lookup-table on managed side:
static concurrentdictionary<long, safebuffer> handles = new ...(); static long nexthandle = 0; static long getnexthandle(safebuffer buffer) { var handle = interlocked.increment(ref nexthandle); handles.add(handle, buffer); return handle; }
you call getnexthandle
before calling unmanaged code. on completion remove handle handles
dictionary.
a handle arbitrary long
stable (does not change) , can passed unmanaged code.
Comments
Post a Comment