lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Sorry for the typos and missing links.. I'm on mobile.

There are several solutions :

1. Use another time class. .NET has a ton of timers most of which dispatch on a single thread in a non reentrant way. They are less precise but easier to work with.

2. Set the synchronization object of the timer to some UI element for automatic dispatching.

3. Use a Dispatcher or a SynchronizationContext to dispatch execution on the thread you want.

4. Set AutoReset to false - this should suffice to work (you have to manually restart the timer though). I would consider using a lock to handle concurrency in a safe way, though.

Note that as far as I know, Lua and LuaInterface will not complain if you use it from different threads as long as it's only one thread at the time.

I might be wrong though.

Shameless plug: you can also check other interface layers for C# and Lua like NLua, SharpLua, MoonSharp, UniLua, and KopiLua. As I'm the author of one of these I listed them in random order but all are good ;) None will help you much in this scenario but should be easier to handle on other aspects.


Il 18/nov/2014 11:25 "Geoff Smith" <spammealot1@live.co.uk> ha scritto:
Hello
 
I have been using LuaInterface for a little while, I have got on pretty well with it so far until I hit this difficult problem. The documentation for it doesn't really help me much on this issue, so hopefully someone here might be able to assist please.
 
I wanted to add a feature where I can create timers on the Lua side with something like
 
timerRefNum = myAPI.createTimer(1000, myCallbackHandler)     -- 1 sec timer
 
then at the bottom of my Lua script I might have something like
 
while true do
   myApi.sleep(100) -- Lua sleeps for 100 mS while nothing much to do
end
 
I am not the most experienced C# coders, but the outline for this code on the C# side seemed fairly easy.
 
I create a System.Timers.Timer for each Lua createTimer() call and add a c# ElapsedEvent handler which then calls the associated Lua function.
 
After having written the C# code I ran a Lua test script with 2 separate timers firing at 500 mS and 1000 mS intervals, with 2 different Lua handlers.  This appeared to work fine and ran for 15 minutes or so before crashing. :(
 
Of course my solution is fatally flawed, what I overlooked was that the main Lua thread will be executing in Windows thread "x", then timer 1 fires and that C# handler will run in thread "'y", the second timer fires and that runs in thread "z"
 
As Lua / LuaInterface isn't  threadsafe that is what I believe is causing the crash. I am struggling now to see how I would implement this timer functionality properly and threadsafe.
 
Any ideas or links to similar example code snippets would be much appreciated. Thanks
 
Regards Geoff