Calling jslib function from async C# class method #413
-
When I try to call a jslib function (eg: using UnityEngine;
using System.Runtime.InteropServices;
public class GameController : MonoBehaviour {
[DllImport("__Internal")]
private static extern void SomeDispatch ();
public async void SomeMethod () {
// Mock async task
await Task.Delay(1000);
#if UNITY_WEBGL == true && UNITY_EDITOR == false
SomeDispatch();
#endif
}
} If I change the C# class method to be synchronous, removing the using UnityEngine;
using System.Runtime.InteropServices;
public class GameController : MonoBehaviour {
[DllImport("__Internal")]
private static extern void SomeDispatch ();
public void SomeMethod () {
#if UNITY_WEBGL == true && UNITY_EDITOR == false
SomeDispatch();
#endif
}
} Unfortunately I cannot change my C# class method to be synchronous – it has to be asynchronous because it waits for the completion of Tasks returned by another asynchronous method. Am I missing something, or do you have any suggestions for how I can work around this issue? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I'm no expert with how Unity and C# async/await play together, but I think the issue is caused by the async function being called on another thread; unable to call the static function, resulting in the execution silently failing/hanging. I fixed the issue by using the third-party package UniTask so that async functions are executed on the player loop, replacing all I would still be interested in knowing the reasons why the original approach did not work, and I think it could be helpful to document this use case. |
Beta Was this translation helpful? Give feedback.
-
Hi! I'm currently not nearby computer, so excuse my somewhat shorter answer. But are you sure it has to do with the fact it is asynchronous? Maybe something is happing at your React application such as re-render which can cause the event listener to be unbound. Have you set up some sort of effect to ensure you're having the latest instance? If it would be possible, sharing some React code might help me narrow down the problem. Another thing you could try is to move the execution of the external method to the Update cycle of Unity and use a timer rather than awaiting a Delay just to ensure the problem is not related to it being asynchronous. I hope this helps you, keep me posted! |
Beta Was this translation helpful? Give feedback.
I'm no expert with how Unity and C# async/await play together, but I think the issue is caused by the async function being called on another thread; unable to call the static function, resulting in the execution silently failing/hanging.
I fixed the issue by using the third-party package UniTask so that async functions are executed on the player loop, replacing all
Tasks
in my code withUniTask
.I would still be interested in knowing the reasons why the original approach did not work, and I think it could be helpful to document this use case.