c# - 如何在 C# 中捕获 Lua 异常

标签 c# multithreading exception lua wndproc

我正在使用名为 LuaInterface 的程序集在我的 C# 应用程序中运行 lua 代码。在 lua 执行期间,我创建了一些 WinForms 并将事件处理程序(lua 方法)映射到它们。

问题是 doString(又名 runLuaCode)方法只运行 init 例程和构造函数。这很好并且是有意的,但是 doString 函数是非阻塞的,所以函数返回时 Lua-created-Forms 仍然存在。这意味着在构造函数期间未引发的任何异常(null-ref 等)都不会由 lua 错误处理一直崩溃到我的编辑器的 wndProc - 这很可能会杀死我的编辑器并进行错误处理几乎不可能。

有没有办法创建一个新的线程/进程/AppDomain 来处理它自己的 WndProc,以便只有这个子任务需要处理异常?

我是否应该在 doString 中用 lua 中的 while 循环阻止我的编辑器直到表单关闭?

我还有哪些其他选择?

非常感谢关于此事的任何建议!

最佳答案

又一个 Lua 爱好者!!最后! :) 我也在考虑在我的 .NET 应用程序中使用 Lua 编写宏脚本。

我不确定我明白了。我写了一些示例代码,它似乎工作正常。围绕 DoString 的简单 try catch 获取 LuaExceptions。除非您显式创建新线程,否则 DoString 会阻塞主线程。如果是新线程,则适用正常的 .NET 多线程异常处理规则。

例子:

public const string ScriptTxt = @"
luanet.load_assembly ""System.Windows.Forms""
luanet.load_assembly ""System.Drawing""

Form = luanet.import_type ""System.Windows.Forms.Form""
Button = luanet.import_type ""System.Windows.Forms.Button""
Point = luanet.import_type ""System.Drawing.Point""
MessageBox = luanet.import_type ""System.Windows.Forms.MessageBox""
MessageBoxButtons = luanet.import_type ""System.Windows.Forms.MessageBoxButtons""

form = Form()
form.Text = ""Hello, World!""
button = Button()
button.Text = ""Click Me!""
button.Location = Point(20,20)
button.Click:Add(function()
        MessageBox:Show(""Clicked!"", """", MessageBoxButtons.OK) -- this will throw an ex
    end)   
form.Controls:Add(button)
form:ShowDialog()";

        private static void Main(string[] args)
        {
            try
            {
                var lua = new Lua();
                lua.DoString(ScriptTxt);
            }
            catch(LuaException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch(Exception ex)
            {
                if (ex.Source == "LuaInterface")
                {
                    Console.WriteLine(ex.Message);
                }
                else
                {
                    throw;
                }
            }

            Console.ReadLine();
        } 

LuaInterface 有一个很好的文档,其中解释了棘手的错误处理。

http://penlight.luaforge.net/packages/LuaInterface/#T6

希望对你有所帮助。 :)

关于c# - 如何在 C# 中捕获 Lua 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4942346/

相关文章:

java - ExecutorService 的 invokeAll() 会同时运行任务,或者完全取决于硬件(运行执行程序服务的地方)和网络

java - 线程中的异常被写入 System.err 而不是被捕获

python - 如何记录 Python 3 异常,但没有其堆栈跟踪?

java - 等待功能不起作用 Android Studio

c# - System.Linq.IOrderedQueryable' 在尝试使用 Skip 方法时不包含 'Skip' 错误的定义

c# - 如何在c#中查看groupbox内的所有项目

c# - 有没有一种方法可以像使用 C# 的 MS Office Excel 一样创建/读取 LibreOffice 电子表格?

java - Android -- 如何使用 3 个 ImageView 切换 View ?

c++ - catch-all-rethrow 与根本没有 try-catch block 有什么不同吗?

c# - 为什么System.IO是这样实现的