Handling Multi-Threading#
By nature, using a Task introduces the concept of multi-threading. Unfortunately, Unity is not a multi-threaded environment. This is to ensure thread-safety for Unity rendering functionality. To this end, the majority of Unity functions will crash/break when called outside of the main thread.
In “Chess” to ensure that the server return calls can be run on the client without an exception; the WebCallback class is used. This is a private class defined at the bottom of the WebServices class.
The WebCallback class uses the the WebServices Singleton Update function:
1public void Update()
2{
3 // Run all delayed calls this frame on the main thread
4 foreach (WebCallback callback in _callbacks)
5 callback.Invoke();
6
7 // Clear out delayed calls
8 _callbacks.Clear();
9}
This ensures callbacks from all threads outside the main thread are run on the main thread.
In “Chess” you can see this utilized in many AXR function calls. For example in OnSessionChanged:
1_callbacks.Add(new WebCallback(val => {
2 bool isHost = _session.HostUid == _user.Uid;
3 _matchFoundEvent?.Invoke(new MatchData() { isHost = isHost });
4}));