Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | madgit | |
Old Version | Published before Godot 3 was released. |
Hi,
Has anyone got Threads going from C# scripts in G3RC2? Mine is crashing immediately I try to thread.Start(obj, “method”). Is this supposed to be working from C# scripts atm?
Briefly I’m just trying to get a simple producer-consumer queue going, with the main thread putting stuff onto the queue and the background (Start-ed) thread consuming off the queue. Crashes even when the consumer background thread does nothing, though, simply when it’s Start-ed.
Did a small rewrite to start the Thread from GDScript, and for the Thread.start()ed script to be written in GDScript that then calls onto my C# stuff. This still fails, although the Thread will start successfully (I can see a debug print coming out from the Threaded GDScript code) but fails with the Windows exception at the point it tries to call out to the C# code.
In fact even if I try to call a totally non-existent C# method from the threaded GDScript, I still get the Windows exception rather than a “method not found” type error. So it must be something to do with the C# engine being run up whilst in a Thread blowing up, before it even gets as far as checking for valid methods etc.
Anyone got C# code successfully running in a Thread?
madgit | 2018-01-24 14:16
In this issue I raised :
the solution has been presented that you must manually attach() and detach() the thread when created from GDScript (and it doesn’t work from C# at present).
Thus the example solution by neikeq in the issue above is :
func _ready():
t = Thread.new()
t.start(self, "_thread_callback")
func _thread_callback():
GodotSharp.attach_thread()
# ...
GodotSharp.detach_thread()
Which resolves my issue perfectly.
Edit: one final wrinkle is that I’ve found it won’t work unless you’re passing at least one parameter to the Thread.start()ed GDScript method, even if it’s only a dummy. So the above example will need t.start(self, “_thread_callback”,“dummy”) and then func _thread_callback(dummy):
madgit | 2018-01-24 20:46