mcpiroman / UnityNativeTool

Allows to unload native plugins in Unity3d editor
MIT License
184 stars 19 forks source link

Small threading fix, delay to main thread #19

Closed rogerbarton closed 4 years ago

rogerbarton commented 4 years ago

Previously when calling a function on a worker thread and encountering a load error, setting the pause state would trigger a exception as we use the Unity API on a worker thread.

This is only for Lazy mode, where the thread safety is not yet fully implemented. But it still fixes this issue.

mcpiroman commented 4 years ago

So maybe just extract the dispatching logic to sth like:

void DispatchOnMainThread(Action action)
{
  if(Thread.CurrentThread.ManagedThreadId == _unityMainThreadId)
     action();
  else
     DllManipulatorScript.MainThreadTriggerQueue.Enqueue(action);
}

and use it both here and on previous PR
rogerbarton commented 4 years ago

Yes agreed. However, in the logic of the previous PR there's also an additional bool useMainThreadQueue:

https://github.com/mcpiroman/UnityNativeTool/blob/f4eb21d4089d4a467ac29922c7ea6017228fd0a4/scripts/DllManipulator.cs#L565-L568

I've left it as is in the previous PR (seeing as its only one occurrence) and changed it for these diffs. Or do you see an nice way of doing this?

mcpiroman commented 4 years ago

Yup I forgot about that flag there. You could do something like this but I don't see much sense in doing so

if(useMainThreadQueue)
   DispatchOnMainThread(() => methodInfo.Invoke(null, args));
else
  methodInfo.Invoke(null, args)

so yes, leave this as is, whatever