"Safe handle has been closed" Error

Hello!

I’m using realm in my Unity app, and periodically saving some data asynchronously. But in case the saving process was started and the application was closed, I receive the “Safe handle has been closed” error (at least I’m seeing it on unity editor), even if canceling it on application quitting event.

My code looks like this:

public static async UniTask SaveDataAsync<T>(T dataToSave, CancellationTokenSource cancellationTokenSource) where T : RealmObject
{
    try
    {
        cancellationTokenSource.Token.ThrowIfCancellationRequested();
        
        //the app is running at this point
        await Database.WriteAsync(() =>
        {
            //the app is quitting and cancelation token's IsCancellationRequested is already true
            //and on application quitting event I disposed the db and set it to null, so the following line will not do anything 
            Database?.Add(dataToSave, update: true);
        }, cancellationTokenSource.Token);
    }
    catch (OperationCanceledException)
    {
        Debug.Log("Saving operation was canceled.");
    }
    catch (Exception ex)
    {
        Debug.LogError($"Error saving data: {ex.Message}");
    }
}

And here is the stacktrace for the error:

So actually what is happening - when transaction was open, cancelation was requested, it throws TaskCanceledException, so the transaction starts to dispose, trying to rollback, where the “Safe handle has been closed” error is thrown in a native call of canceling the transaction.

So for specifically the case I encountered - the actual saving part and transaction commit was not even started, so there will be no problems it seems, but my main concern is - what if the application close will happen during transaction.CommitAsync inside realm’s WriteAsync method.

So the questions are:
• Can that scenario result some broken data or just partially overriden data saved in the db? (although in theory the transaction should be either fully done, or nothing done, yes? But the exception is inside transaction rollback)
• What is the proper way to deal with application close for async operations with realm?

By the way - if I have multiple savings started when closing the app - only for the first one I receive the exception, and all others are being successfully canceled.