使用多线程时,C# P/Invoke ODBC32.dll 失败

发布于 2024-10-24 09:10:34 字数 412 浏览 2 评论 0原文

更新:以下错误实际上是由于我错过的一个简单错误造成的。这里唯一真正的信息是疲倦和愚蠢是一个糟糕的组合。

由于与我们被迫使用的 ODBC 驱动程序的某些特定功能有关的原因,我一直在尝试编写一个直接使用的小型应用程序ODBC 调用。由于 C# 2.0 是我最了解的,因此我一直使用对 ODBC32.dll 的 P/Invoke 调用来完成此操作。

我最初编写的代码是多线程的。但我注意到,一旦我跳转线程,我就会收到 AccessViolationExceptions。例如,当我在一个线程中生成对环境和连接的 IntPtr 引用,然后尝试在另一个线程中使用它们来生成语句 (SQLAllocStmt) 时,一切都会弹出。

我确信我可以解决这个问题,但是这有什么明显的原因吗?调用 ODBC32.dll 分配的非托管内存是否以某种方式绑定到特定线程?

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 features 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

潇烟暮雨 2024-10-31 09:10:35

这取决于:

  • odbc 驱动程序:它是什么?
  • 您的代码:您是否在没有意识到的情况下释放了内存?

考虑一下:

  • 您是否真的需要这样做。您不能使用连接字符串或通过命令对象使用特定于驱动程序的命令来控制驱动程序的行为吗?
  • 如果您确实必须这样做,您可以将其隔离到单个 STA 线程中并使用编组或任务队列来简化您的工作吗?
  • 如果您确实必须从多个线程使用它,您不能确保每个线程都有自己的连接和环境吗?

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?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文