Closed JPerryOddGames closed 5 years ago
Please see the following example. The Application.logMessageReceivedThreaded event can be invoked from any thread. It feels messy to implement another async void method just to await one of Unity's YieldInstructions to get back to the main thread
using System;
using UnityEngine;
public class UnitySchedulerAccessExample : IDisposable
{
public UnitySchedulerAccessExample()
{
Application.logMessageReceivedThreaded += OnLogMessageReceived;
}
/// <summary>
/// Callback that can occur on any thread. This must be thread-safe.
/// </summary>
private void OnLogMessageReceived(string condition, string stackTrace, LogType type)
{
// Process the log message
ProcessLogMessageThreadSafe();
// Do something Unity-API related, maybe we want to increment a number on an in-game UI?
// This may fail depending on which thread caused this callback to run
CallSomeUnityAPI();
// Do this to ensure the code is run correctly
UnityScheduler.Run(CallSomeUnityAPI);
}
private void ProcessLogMessageThreadSafe()
{
// Do something here that can safely run on any thread
}
private void CallSomeUnityAPI()
{
// Do something here that must be run on the main thread.
}
public void Dispose()
{
Application.logMessageReceivedThreaded -= OnLogMessageReceived;
}
}
Why not just await new WaitForUpdate()
to get back on the main thread before calling your unity api as described in the documentation?
public class AsyncExample : MonoBehaviour
{
async void Start()
{
// Unity thread
await new WaitForBackgroundThread();
// Background thread
await new WaitForUpdate();
// Unity thread again
}
}
@StephenHodgson Apologies for my confusion, this will indeed solve the issue I was trying to work around
No worries! glad to help
What's the benefit of moving this into its own class? I think it's in the best interest of the utility to have exclusive access to this method.
If there's an action you need to await on, then maybe we should be adding an additional awaiter extension method.