C# P/Invoke into ODBC32.dll failing when using multiple threads
UPDATE: The following error was actually due to a simple bug which I missed. The only real message here that tired and stupid is a bad combination.
For reasons to do with some specific fea开发者_StackOverflowtures of an ODBC driver we're forced to use, I've been trying to write a small application which directly uses ODBC calls. Since C# 2.0 is what I know most, I've been doing this using P/Invoke calls into ODBC32.dll.
The code I've written initially has been multithreaded. But I've noticed that as soon as I jump threads I'm getting AccessViolationExceptions. For instance, when I generate IntPtr references to an Environment and Connection in one thread and then try to use these in another thread in the generation of a Statement (SQLAllocStmt), it all goes pop.
I'm sure I can work around this, but is there some obvious reason for this? Is the unmanaged memory allocated by the calls into ODBC32.dll somehow bound to a particular thread?
This depends on:
- The odbc driver: What is it?
- Your code: Are you freeing the memory without realizing it?
Consider:
- Whether you really need to do this. Can't you control the behaviour of the driver using the connection string, or using driver-specific commands through a command object?
- If you do have to do this, can you isolate it into a single STA thread and use marshalling, or a task queue, to simplify your job?
- If you do have to use it from multiple threads, can't you make sure each thread has it's own Connection and Environment?
精彩评论