diff --git a/Assets/pocketbase-unity/Runtime/Sse/DownloadHandlerSseBase.cs b/Assets/pocketbase-unity/Runtime/Sse/DownloadHandlerSseBase.cs index 8ad664e..340d3f7 100644 --- a/Assets/pocketbase-unity/Runtime/Sse/DownloadHandlerSseBase.cs +++ b/Assets/pocketbase-unity/Runtime/Sse/DownloadHandlerSseBase.cs @@ -4,6 +4,7 @@ */ using System.Text; +using System.Threading; using UnityEngine.Networking; namespace PocketBaseSdk @@ -12,6 +13,13 @@ public abstract class DownloadHandlerSseBase : DownloadHandlerScript { private readonly StringBuilder _currentLine = new(); private readonly Decoder _utf8Decoder = Encoding.UTF8.GetDecoder(); + private static readonly SynchronizationContext UnitySyncContext; + + static DownloadHandlerSseBase() + { + // Capture Unity's main thread SynchronizationContext on class initialization + UnitySyncContext = SynchronizationContext.Current; + } protected DownloadHandlerSseBase(byte[] buffer) : base(buffer) { @@ -34,11 +42,24 @@ protected override bool ReceiveData(byte[] newData, int dataLength) if (c == '\n') { - OnNewLineReceived(_currentLine.ToString()); + string line = _currentLine.ToString(); _currentLine.Clear(); + + // Marshal to Unity main thread before processing + if (UnitySyncContext != null) + { + string lineToProcess = line; // Capture for closure + UnitySyncContext.Post(_ => OnNewLineReceived(lineToProcess), null); + } + else + { + OnNewLineReceived(line); + } } else + { _currentLine.Append(c); + } } return true; @@ -47,7 +68,20 @@ protected override bool ReceiveData(byte[] newData, int dataLength) protected override void CompleteContent() { if (_currentLine.Length > 0) - OnNewLineReceived(_currentLine.ToString()); + { + string line = _currentLine.ToString(); + + // Marshal to Unity main thread before processing + if (UnitySyncContext != null) + { + string lineToProcess = line; // Capture for closure + UnitySyncContext.Post(_ => OnNewLineReceived(lineToProcess), null); + } + else + { + OnNewLineReceived(line); + } + } } } } \ No newline at end of file