分享一个 C#程序的神秘 bug,顺便问问为什么会这样?

6 天前
 BBrother

在以下代码中,如果注释掉UIDocument UIDocument = new UIDocument(Document);这一行代码(倒数第二行),运行后可以正常输出到init finish,但是这行代码如果存在则只能输出到$"2, {clientId.GetGUID()}"这一行,然后会报运行时错误:

未经处理的异常:  System.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。

为什么会存在这种后面还没运行到的代码可以影响前面代码的报错?

 [STAThread]
        static void Main(string[] args)
        {
            // 初始化
            Init();
            Product revitInstance = Product.GetInstalledProduct();
            Console.WriteLine("1");
            var clientId = new ClientApplicationId(Guid.NewGuid(), "testing", "ADSK.Username");
            Console.WriteLine($"2, {clientId.GetGUID()}");
            revitInstance.Init(clientId, "I am authorized by Autodesk to use this UI-less functionality.");
            Console.WriteLine("3");
            Autodesk.Revit.ApplicationServices.Application Application = revitInstance.Application;
            Console.WriteLine("4");
            Document Document = Application.OpenDocumentFile(inputPath);
            Console.WriteLine("5");
            UIDocument UIDocument = new UIDocument(Document);
            Console.WriteLine("init finish");
            
            ......
        }
417 次点击
所在节点    问与答
7 条回复
idealhs
6 天前
你这是 Unity 吧?先说清楚环境,.NET 还是 mono 啥的
BBrother
6 天前
@idealhs #1 .net framework 4.8 控制台应用程序,引用了 revit 的 dll
idealhs
6 天前
@BBrother 单步调试吧,或者你把全部代码发出来看看,你这 Init(); 就不知道干啥了,跑不起来
BBrother
6 天前
@idealhs #3 init 可以注释掉不影响这个现象的发生,单步不了,环境比较特殊,需要在一台没有 vs 的机器上运行。
Eiden
6 天前
vs 可以远程调试的
a33291
6 天前
@BBrother 先确认在开发机是否正常,然后用依赖检查工具检查在目标机器上的 revit dll 的依赖是否满足,特别是运行时环境(应该是 vc++)
idealhs
6 天前
@BBrother #4 没法开发机调的话,上 Visual Studio remote debugger
https://learn.microsoft.com/en-us/visualstudio/debugger/remote-debugging?view=vs-2022

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1052366

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX