您的位置:首页 > 编程语言 > Lua

C#+NLua实现将Lua代码在主线程上执行

2017-10-18 18:39 225 查看
本文示例下载

1.C#与Lua的交互请参考我以前的文章Lua结合C#调用C++或者C的函数

2.在C#中,如何将一片代码片段放在主线程执行呢?对于Winform程序:

public void ExecuteMethodInMainThread()
{
if (this.InvokeRequired)
{
this.Invoke(new Action<Action>(ExecuteMethodInMainThread));
return;
}
///填写要在主线程上执行的代码
}


对于WPF:

public void ExecuteMethodInMainThread()
{
this.Dispather.Invoke(new Action(()=>
{
///填写要在主线程上执行的代码
}));

}


3.在Lua中,将指定代码片段在主线程中执行:

a.lua中的匿名函数:

local fun=function()
return 5;
end
local result=fun();--b值为5


b.C#中的委托的作用之一就是可以将方法作为参数:

public void Dosomething(Action a)
{
a();
}
public void Delay()
{
Thread.Sleep(3000);
}
Dosomething(Delay);


按照这个思路,Lua中的function也是函数,是否可以当作委托传过来?

答案是肯定的。

在C#中,申明如下函数,然后在Lua中调用:

public Form1()
{
InitializeComponent();
lua = new NLua.Lua();
lua["this"] = this;
lua.LoadCLRPackage();
}
public void ExecuteMethodInMainThread(Action a)
{
if (this.InvokeRequired)
{
this.Invoke(new Action<Action>(ExecuteMethodInMainThread), a);
return;
}
a();
}


然后在test.lua中填写如下:

import("System.Threading");
function UpdateTime()
while(true) do
local t=os.date("*t");
str=t.hour..":"..t.min..":"..t.sec;
this:ExecuteMethodInMainThread(
function()
this.label1.Text=str;
end
);
Thread.Sleep(500);
end
end
UpdateTime();


其中label1为主窗体上的一个label,设置为public,不然在Lua中访问不到。

最后调用Lua文件:

private void button1_Click(object sender, EventArgs e)
{
new Thread(() =>
{
lua.DoFile("test.lua");

}).Start();

}


以上实现了在Lua中,使用线程更新UI的目的。

本文示例下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lua c#