Skip to content

Instantly share code, notes, and snippets.

@danielbierwirth
Last active July 1, 2024 13:39
Show Gist options
  • Save danielbierwirth/834c42c8343a9e10ea4bdeaee31e0290 to your computer and use it in GitHub Desktop.
Save danielbierwirth/834c42c8343a9e10ea4bdeaee31e0290 to your computer and use it in GitHub Desktop.
Unity C# script to execute task asynchronously in background and process result on Unity main thread. The script can be used to run compute intensive or other operations such as HTTP stream listener in background. The UnityMainThreadDispatcher is used to move the result of async task to the main thread.
using System;
using System.Threading.Tasks;
using UnityEngine;
using PimDeWitte.UnityMainThreadDispatcher;
/// <summary>
/// A Unity C# script to execute task asynchronously and process result on Unity main thread.
/// </summary>
/// Note: This script utilizes the UnityMainThreadDispatcher
/// from https://github.com/PimDeWitte/UnityMainThreadDispatcher package
/// to dispatch calls to the main thread
public class AsyncTaskRunner : MonoBehaviour
{
public event Action<bool> OnAsyncTaskCompletion;
private void Start()
{
// Attach action for demo purposes
OnAsyncTaskCompletion += HandleTaskCompletion;
// Initiate background operation
Task.Run(() => ExecuteBackgroundOperationAsync());
}
/// <summary>
/// Executes an operation asynchronously to avoid blocking Unity's main render thread.
/// </summary>
private async Task ExecuteBackgroundOperationAsync()
{
// Emulate background operation execution
await Task.Delay(100);
OnAsyncTaskCompletion?.Invoke(true);
}
private void HandleTaskCompletion(bool taskCompleted)
{
UnityMainThreadDispatcher.Instance().Enqueue(() => {
// Process the result on the main thread
// This could be updating UI or GameObjects
Debug.Log($"Async Operation Result: {taskCompleted}");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment