gpt4 book ai didi

c# - 后台线程上的 new System.Transactions.TransactionScope() 会停止程序

转载 作者:行者123 更新时间:2023-12-02 02:58:55 24 4
gpt4 key购买 nike

我有一些使用System.Transactions.TransactionScope的代码,创建事务范围的新实例只会停止程序。

没有异常或消息,程序只是停止,Visual Studio 返回代码编辑模式。该过程完全消失了。事件查看器中没有异常、消息或事件。

我有另一个测试应用程序使用 TransactionScope 没有问题,所以它不应该是环境问题。

我只是不知道如何获取异常详细信息。我已经在 Visual Studio 中的“调试”->“异常”对话框中打开了所有“抛出”复选框,希望 VS 在抛出异常时自动中断,但事实并非如此。

谁能帮我找出程序退出的原因吗?

编辑:我刚刚发现了一些新东西。 TransactionScope 是通过 ThreadPool.QueueUserWorkItem 在后台线程上运行的方法中创建的。如果我直接在主应用程序线程上调用该方法,这个问题就会消失。所以现在我的问题是“在线程池线程上使用 TransactionScope 有什么问题?”。请注意,在调用新线程之前,我没有启动事务范围,这一切都在线程池线程上运行的一个方法内。

最佳答案

我发现问题了。它是运行我的计算机的柔软的有机组件。

ThreadPool.QueueUserWorkItem() 将开始在线程池线程上工作。这意味着 background thread 。该代码在测试控制台应用程序中运行,当然我忘记在 Main() 中添加任何内容以阻止程序在调用 ThreadPool.QueueUserWorkItem() 后退出>。这意味着当我按 F10 进入下一行时,程序实际上已经停止,因此调试器自行关闭。

我所做的修复它的只是在 Program.Main() 末尾添加对 Console.ReadKey() 的调用,现在一切都工作得很好。请注意,该问题与 System.Transactions.TransactionScope 或线程池线程无关。无论我将断点放在哪一行,它都会发生。

注意:
如果您认为我应该看到 ThreadAbortException,那么阅读上面链接的文章将会指出为什么没有发生这种情况。这是直接引用:

When the runtime stops a background thread because the process is shutting down, no exception is thrown in the thread. However, when threads are stopped because the AppDomain.Unload method unloads the application domain, a ThreadAbortException is thrown in both foreground and background threads.

关于c# - 后台线程上的 new System.Transactions.TransactionScope() 会停止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/839119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com