Exception when RemoveRoom not called on main thread.

Description, details and error message(s)

As a convenience I am trying to wrap some Coherence SDK APIs in Task so that I can make more use of async/await syntax. Doing so produces an error that UnityWebRequest used by the RemoveRoom API can only be called from the main thread.

Expected behaviour

RemoveRoom and other APIs can be called from Task.

Screenshots

UnityEngine.UnityException: Create can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
  at (wrapper managed-to-native) UnityEngine.Networking.UnityWebRequest.Create()
  at UnityEngine.Networking.UnityWebRequest..ctor (System.String url, System.String method) [0x00008] in <f4953a2b498b49e686c06a48e7c10c85>:0 
  at Coherence.Runtime.Request.ExecuteCustom (System.String endpoint, System.String path, System.String method, System.String body, System.Action`1[T] callback) [0x0005b] in .\Library\PackageCache\io.coherence.sdk@1.0.0\Coherence.Runtime\Request.cs:59 
  at Coherence.Cloud.RequestFactory.SendCustomRequest (System.String endpoint, System.String path, System.String method, System.String body, System.Action`1[T] callback) [0x00001] in .\Library\PackageCache\io.coherence.sdk@1.0.0\Coherence.Runtime\Cloud\Requests\RequestFactory.cs:294 
  at Coherence.Cloud.ReplicationServerRoomsService.RemoveRoom (System.UInt64 uniqueID, System.String secret, System.Action`1[T] onRequestFinished) [0x0003b] in .\Library\PackageCache\io.coherence.sdk@1.0.0\Coherence.Runtime\Cloud\Rooms\ReplicationServerRoomsService.cs:88 
  at MainMenu.LobbyUiController.<LeaveRoom>b__31_0 () [0x00012] in C:\dev\kevin\unity-rts\unity-rts\Assets\scripts\MainMenu\LobbyUiController.cs:151 
  at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in <605bf8b31fcb444b85176da963870aa7>:0 
  at System.Threading.Tasks.Task.Execute () [0x00000] in <605bf8b31fcb444b85176da963870aa7>:0

How to reproduce

ReplicationServerRoomsService _replicationServerRoomsService
  ??= new ReplicationServerRoomsService();
await Task.Run(() =>
{
    TaskCompletionSource<string> t = new();

    _replicationServerRoomsService .RemoveRoom(
        12345,
        "12345",
        (RequestResponse<string> result) => { t.TrySetResult(result.Result); });

    return t.Task;
});

Environment

SDK: v1.0.0
Engine: v0.61.5
Unity: 2022.3.4f1

1 Like

It looks like there is a RemoveRoomAsync for this purpose, which I just noticed :sweat_smile:.

3 Likes