Skip to content

Commit dd52d89

Browse files
authored
Small threading fix, delay to main thread (#19)
* Small threading fix, delay to main thread Previously when calling a function on a worker thread and encountering a load error, pausing 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. * Extract DispatchOnMainThread
1 parent f4eb21d commit dd52d89

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

scripts/DllManipulator.cs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,7 @@ internal static void LoadTargetFunction(NativeFunction nativeFunction, bool igno
503503
if (!ignoreLoadError)
504504
{
505505
dll.loadingError = true;
506-
Prop_EditorApplication_isPaused.Value?.SetValue(null, true);
506+
DispatchOnMainThread(() => { Prop_EditorApplication_isPaused.Value?.SetValue(null, true); });
507507
throw new NativeDllException($"Could not load DLL \"{dll.name}\" at path \"{dll.path}\".");
508508
}
509509

@@ -529,7 +529,7 @@ internal static void LoadTargetFunction(NativeFunction nativeFunction, bool igno
529529
if (!ignoreLoadError)
530530
{
531531
dll.symbolError = true;
532-
Prop_EditorApplication_isPaused.Value?.SetValue(null, true);
532+
DispatchOnMainThread(() => { Prop_EditorApplication_isPaused.Value?.SetValue(null, true); });
533533
throw new NativeDllException($"Could not get address of symbol \"{nativeFunction.identity.symbol}\" in DLL \"{dll.name}\" at path \"{dll.path}\".");
534534
}
535535

@@ -568,6 +568,18 @@ private static void InvokeCustomTriggers(List<Tuple<MethodInfo, bool>> triggers,
568568
methodInfo.Invoke(null, args);
569569
}
570570
}
571+
572+
/// <summary>
573+
/// Ensure the action is executed on the main thread. Executes immediately if on the main thread already,
574+
/// otherwise the action is added to a queue <see cref="DllManipulatorScript.MainThreadTriggerQueue"/>
575+
/// </summary>
576+
private static void DispatchOnMainThread(Action action)
577+
{
578+
if(Thread.CurrentThread.ManagedThreadId == _unityMainThreadId)
579+
action();
580+
else
581+
DllManipulatorScript.MainThreadTriggerQueue.Enqueue(action);
582+
}
571583

572584
/// <summary>
573585
/// Logs native function's call to file. If that file exists, it is overwritten. One file is maintained for each thread.

0 commit comments

Comments
 (0)