Search Unity

Resolved Issue with await and TaskCompletionSource

Discussion in 'Editor & General Support' started by RWD_MichaelK, Mar 29, 2021.

  1. RWD_MichaelK

    RWD_MichaelK

    Joined:
    Mar 29, 2021
    Posts:
    2
    I'm working on a project that makes use of a C# wrapper around a C++ DLL. Said C++ DLL exposes functions that take a callback function pointer. These functions are wrapped as Task-based methods in the C# wrapper. This is done by creating a TaskCompletionSource that is used within the callback that is sent to the C++ function. This works fine in our .Net unit tests, but throws a NullReferenceException when trying to reference the TaskCompletionSource in the callback from Unity. This exception throws even when trying to check if the TaskCompletionSource is null, so it seems like an internal error happening with the captured variable. I've attached a minimal example that contains both a Unity project and source for the native and managed DLLs. Any help with this issue would be greatly appreciated. Thanks in advance.

    EDIT: This is with Unity 2020.1.12f1
     

    Attached Files:

    Last edited: Mar 29, 2021
  2. RWD_MichaelK

    RWD_MichaelK

    Joined:
    Mar 29, 2021
    Posts:
    2
    I've managed to solve the issue. It looks like the Mono Runtime was freeing the callback lambda, even though .Net Runtime wasn't. The solution was to allocate a GCHandle to the callback, assign the handle (instead of the lambda) to the Task's AsyncState, and free said handle in the callback.