JsonUtility.ToJson from background thread

Hello, I’m trying to make a very little internal server for debugging purposes in my game that allows for data transfer through HTTP so that I can change some values during runtime even without playing from the editor. The issue is that it only works once, because the first time I access the data i need (I’m not even changing them yet) the call to JsonUtility.ToJson() fails an Assertion “CurrentThreadIsMainThread()”. Data is successfully retrieved, but from that moment onward Nothing works anymore. The official documentation says Jsonutility can be called from background threads so I don’t really know where it is failing. Here’s the snippet:

protected override DBQualitySettings RefObject => QualitySystem.Instance.CurrentQualitySettings;

        public override void OnGet(string path, HttpListenerRequest request, HttpListenerResponse response)
        {
            if (path == AbsolutePath)
            {
                response.ContentType = "application/json";
                response.StatusCode = 200;
                var obj = RefObject;
                var json = JsonUtility.ToJson(obj, true); //<-- THIS LINE
                var bytes = Encoding.UTF8.GetBytes(json);
                response.ContentLength64 = bytes.LongLength;
                response.OutputStream.Write(bytes, 0, bytes.Length);
                response.Close();
            } else base.OnGet(path, request, response);
        }

OnGet is called from another thread and this is the only connection to Unity APIs. DNQualitySettings is a ScriptableObject.

It may be a bug. Workaround would be to switch to a different Json serializer in the meantime.

Very little can be called from background threads. Most likely the above cannot be. You assert that JSON can be. I am surprised and skeptical of that.

As always with Unity, do it in the foreground thread, or else write your own marshaler to get it off the background thread and all finished up on the main thread once you have what you need.

Delegate queue to marshal tasks from other threads to the main thread:

https://discussions.unity.com/t/850153/2