realm / realm-dotnet

Realm is a mobile database: a replacement for SQLite & ORMs
https://realm.io
Apache License 2.0
1.25k stars 165 forks source link

DeleteRealm wallways say file locked #2455

Closed carbonete closed 3 years ago

carbonete commented 3 years ago

Goals

Delete local realm file and logout.

Expected Results

After dispose Instance, file is free to delete.

Actual Results

System.IO.IOException HResult=0x80070020 Message=The process cannot access the file 'C:\Users\xxxxxxxxxxxxxxx.realm' because it is being used by another process. Source=System.IO.FileSystem StackTrace: at System.IO.FileSystem.DeleteFile(String fullPath) at System.IO.File.Delete(String path) at Realms.Realm.DeleteRealm(RealmConfigurationBase configuration)

Steps to Reproduce

Run debugging and always receive this error. Instance is closed . image

Code Sample

        public async void Logout()
        {
            if (RealmUser != null)
            {
                if (RealmSyncConfig != null)
                {
                    await RealmInstance.GetSession().WaitForUploadAsync();
                    RealmInstance.Dispose();
                    Realm.DeleteRealm(RealmSyncConfig);
                }
                await RealmUser.LogOutAsync();
                RealmSyncConfig = null;
            }
        }

Version of Realm and Tooling

Installed Version: Professional

Visual C++ 2019 00435-60000-00000-AA316 Microsoft Visual C++ 2019

ADL Tools Service Provider 1.0 This package contains services used by Data Lake tools

ASA Service Provider 1.0

ASP.NET and Web Tools 2019 16.10.526.50910 ASP.NET and Web Tools 2019

ASP.NET Web Frameworks and Tools 2019 16.10.526.50910 For additional information, visit https://www.asp.net/

Azure App Service Tools v3.0.0 16.10.526.50910 Azure App Service Tools v3.0.0

Azure Data Lake Node 1.0 This package contains the Data Lake integration nodes for Server Explorer.

Azure Data Lake Tools for Visual Studio 2.6.3000.0 Microsoft Azure Data Lake Tools for Visual Studio

Azure Functions and Web Jobs Tools 16.10.526.50910 Azure Functions and Web Jobs Tools

Azure Logic Apps Tools for Visual Studio 1.0 Add-in for the Azure Resource Group project to support the Logic App Designer and template creation.

Azure Stream Analytics Tools for Visual Studio 2.6.3000.0 Microsoft Azure Stream Analytics Tools for Visual Studio

C# Tools 3.10.0-4.21269.26+029847714208ebe49668667c60ea5b0a294e0fcb C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools 1.10 Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Dotfuscator Community Edition 6.3.0+8b29d6f4a2 PreEmptive Protection - Dotfuscator CE

Extensibility Message Bus 1.2.6 (master@34d6af2) Provides common messaging-based MEF services for loosely coupled Visual Studio extension components communication and integration.

Fabric.DiagnosticEvents 1.0 Fabric Diagnostic Events

GitHub.VisualStudio 2.11.106.19330 A Visual Studio Extension that brings the GitHub Flow into Visual Studio.

IntelliCode Extension 1.0 IntelliCode Visual Studio Extension Detailed Info

Liquid Studio 2021 - Graphical WSDL Editor 19.0.10 Liquid Studio 2021 - Graphical WSDL Editor

The WSDL Editor abstracts much of the complexity of the WSDL standard, presenting the structure of the WSDL without showing the unnecessary complexity.

This provides a view that makes understanding and editing your WSDL document simple. Access to the full range of related facets is available via the properties window and the WSDL can be edited directly within the Source view.

Embedded XML Schema within your WSDL can be displayed and edited within an XML Schema Editor View, making defining types for your WSDL simple.

Liquid Studio 2021 - JSON Schema Editor 19.0.10 Liquid Studio 2021 - JSON Schema Editor

The JSON Schema Editor abstracts away the complexities of JSON Schema structure by providing an intuitive graphical drag and drop user interface.

The Graphical JSON Schema Designer included in Liquid Studio massively simplifies visualizing, authoring and navigating complex JSON Schemas. The Graphical JSON Schema Editor provides an interactive logical view of the JSON Schema enabling simple and intuitive editing and validation of the JSON Schema, without compromising the ability to work with all the complexities of the Internet Engineering Task Force draft 4.0 JSON Schema Standard.

Liquid Studio 2021 - Web Service Test Client 19.0.10 Liquid Studio 2021 - Web Service Test Client

The Web Service Test Client makes it quick and easy to make ad-hoc calls to a web service. Simply select the web service URL, pick the web method from the list, amend any values in the generated SOAP request, and view the results.

Liquid Studio 2021 - XML Schema Editor 19.0.10 Liquid Studio 2021 - XML Schema Editor

The XML Schema Editor abstracts away the complexities of XSD structure by providing an intuitive graphical drag and drop user interface.

The Graphical XML Schema Designer included in Liquid Studio massively simplifies visualizing, authoring and navigating complex XML Schemas. The Graphical XSD Editor provides an interactive logical view of the XML Schema enabling simple and intuitive editing and validation of the XSD, without compromising the ability to work with all the complexities of the W3C XML Schema standard.

Liquid Studio 2021 - XPath Expression Builder 19.0.10 Liquid Studio 2021 - XPath Expression Builder

The XPath Expression Builder tool allows you to construct and view the results of your query as you type.

It attaches itself to the active XML Editor, so any XML panel in the environment can be queried.

The XPath Query Editor comes with Intellisense, which is intelligently taken from the content of the current XML document. The results of the XPath expression can then be seen in the active XML Editor.

Liquid XML Objects 19.0.10 Generates code from XML Schemas for C# and Visual Basic

Microsoft Azure HDInsight Azure Node 2.6.3000.0 HDInsight Node under Azure Node

Microsoft Azure Hive Query Language Service 2.6.3000.0 Language service for Hive query

Microsoft Azure Service Fabric Tools for Visual Studio 16.10 Microsoft Azure Service Fabric Tools for Visual Studio

Microsoft Azure Stream Analytics Language Service 2.6.3000.0 Language service for Azure Stream Analytics

Microsoft Azure Stream Analytics Node 1.0 Azure Stream Analytics Node under Azure Node

Microsoft Azure Tools 2.9 Microsoft Azure Tools for Microsoft Visual Studio 2019 - v2.9.40423.1

Microsoft Continuous Delivery Tools for Visual Studio 0.4 Simplifying the configuration of Azure DevOps pipelines from within the Visual Studio IDE.

Microsoft JVM Debugger 1.0 Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft Library Manager 2.1.113+g422d40002e.RR Install client-side libraries easily to any web project

Microsoft MI-Based Debugger 1.0 Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual C++ Wizards 1.0 Microsoft Visual C++ Wizards

Microsoft Visual Studio Tools for Containers 1.2 Develop, run, validate your ASP.NET Core applications in the target environment. F5 your application directly into a container with debugging, or CTRL + F5 to edit & refresh your app without having to rebuild the container.

Microsoft Visual Studio VC Package 1.0 Microsoft Visual Studio VC Package

Mono Debugging for Visual Studio 16.10.15 (552afdf) Support for debugging Mono processes with Visual Studio.

Multilingual App Toolkit 4.0 Multilingual App Toolkit helps you localize your Windows Store app by providing file management, pseudo and machine translation, translation editor, and build integration. http://aka.ms/matinstall

Node.js Tools 1.5.30310.1 Commit Hash:e550dd1b679956810ccace4368dbc7a64443213b Adds support for developing and debugging Node.js apps in Visual Studio

NuGet Package Manager 5.10.0 NuGet Package Manager in Visual Studio. For more information about NuGet, visit https://docs.nuget.org/

ProjectServicesPackage Extension 1.0 ProjectServicesPackage Visual Studio Extension Detailed Info

Razor (ASP.NET Core) 16.1.0.2122504+13c05c96ea6bdbe550bd88b0bf6cdddf8cde1725 Provides languages services for ASP.NET Core Razor.

SQL Server Data Tools 16.0.62105.04180 Microsoft SQL Server Data Tools

Syntax Visualizer 1.0 An extension for visualizing Roslyn SyntaxTrees.

Test Adapter for Boost.Test 1.0 Enables Visual Studio's testing tools with unit tests written for Boost.Test. The use terms and Third Party Notices are available in the extension installation directory.

Test Adapter for Google Test 1.0 Enables Visual Studio's testing tools with unit tests written for Google Test. The use terms and Third Party Notices are available in the extension installation directory.

ToolWindowHostedEditor 1.0 Hosting json editor into a tool window

TypeScript Tools 16.0.30429.2002 TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools 3.10.0-4.21269.26+029847714208ebe49668667c60ea5b0a294e0fcb Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools 16.10.0-beta.21262.7+1b23bbeda88ea3cb9be9af777f4c99fa8663df81 Microsoft Visual F# Tools

Visual Studio Code Debug Adapter Host Package 1.0 Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Container Tools Extensions 1.0 View, manage, and diagnose containers within Visual Studio.

Visual Studio Tools for CMake 1.0 Visual Studio Tools for CMake

Visual Studio Tools for Containers 1.0 Visual Studio Tools for Containers

Visual Studio Tools for Kubernetes 1.0 Visual Studio Tools for Kubernetes

VisualStudio.DeviceLog 1.0 Information about my package

VisualStudio.Mac 1.0 Mac Extension for Visual Studio

Xamarin 16.10.000.231 (d16-10@8111164) Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin Designer 16.10.0.115 (remotes/origin/c750fbf1bde3c720d077f51640fe197c6dac7cbe@c750fbf1b) Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin Templates 16.10.5 (355b57a) Templates for building iOS, Android, and Windows apps with Xamarin and Xamarin.Forms.

Xamarin.Android SDK 11.3.0.4 (d16-10/ae14caf) Xamarin.Android Reference Assemblies and MSBuild support. Mono: b4a3858 Java.Interop: xamarin/java.interop/d16-10@f39db25 ProGuard: Guardsquare/proguard/v7.0.1@912d149 SQLite: xamarin/sqlite/3.35.4@85460d3 Xamarin.Android Tools: xamarin/xamarin-android-tools/d16-10@c5732a0

Xamarin.iOS and Xamarin.Mac SDK 14.20.0.10 (0e35b2e0b) Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

DominicFrei commented 3 years ago

Hello @carbonete !

Thank you for that thorough report! :)

We've figured out that there are cases where this could happen. For example the Realm still being in use (due to Sync) when trying to delete it. From my first look at your report it looks like that for me.

Good news: We are in fact working on this right now already: https://github.com/realm/realm-dotnet/pull/2401 (along with https://github.com/realm/realm-core/pull/4768).

carbonete commented 3 years ago

Ok, thanks i will subscribe to follow.

DominicFrei commented 3 years ago

You can keep this issue open too if you want to. I did not want to push you into closing it just because we are aware of it. :) It is a valid issue and the PR is not merged yet. @carbonete

carbonete commented 3 years ago

ok, thanks

nirinchev commented 3 years ago

I'm not sure the PR will resolve the issue - you'll get a more specific exception, but the underlying reason for the file being locked remains - the sync client is being shutdown asynchronously. When you call Dispose on the Realm instance, it will signal the sync client to shutdown but will not await the actual shutdown. While we will be exploring a convenience API in the future, as a stopgap, you can just retry the deletion waiting a few milliseconds between attempts - something like:

public static async Task DeleteWithRetries(RealmConfigurationBase config)
{
    for (var i = 0; i < 100; i++)
    {
        try
        {
            Realm.DeleteRealm(config);
            return;
        }
        catch
        {
            await Task.Delay(50);
        }
    }

    throw new Exception($"Failed to delete the Realm at {config.DatabasePath} after 100 attempts");
}
carbonete commented 3 years ago

@nirinchev Thanks for suggestion. But i test and result is the same in UWP app.

nirinchev commented 3 years ago

Is it possible you have the Realm instance open somewhere else? Dispose-ing of an instance will not close instances open on other threads - e.g.

var config = new SyncConfiguration(...);
var r1 = Realm.GetInstance(config);
var r2 = Realm.GetInstance(config);

r1.Dispose();

will keep r2 open, so you won't be able to delete the Realm file.

carbonete commented 3 years ago

Realm Instance is defined as static, and only one is used.

DominicFrei commented 3 years ago

Realm Instance is defined as static, and only one is used.

@carbonete Would you be able to show us this setup code as well? Maybe you can extract that part into a small, stripped-down example app?

I've played a bit more with master and the changes I'm introducing with https://github.com/realm/realm-dotnet/pull/2401 but I was not able to reproduce your exact problem on my side.

DominicFrei commented 3 years ago

Realm Instance is defined as static, and only one is used.

@carbonete Would you be able to show us this setup code as well? Maybe you can extract that part into a small, stripped-down example app?

I've played a bit more with master and the changes I'm introducing with #2401 but I was not able to reproduce your exact problem on my side.

Ok, this reproduces the exact problem: https://github.com/realm/realm-dotnet/tree/df/reproduction-for-2455

When I add a test (https://github.com/realm/realm-dotnet/commit/2b104da5f3463ae1e9809b9024207b69fb524a52) I see:

System.IO.IOException : 
The process cannot access the file 
'C:\Users\xxxxxxxxxxxxxxxxxxxxxx.realm' because it is being used by another process.

When I then add a delay (https://github.com/realm/realm-dotnet/commit/5eeaa825432b3a2b1365d3c910b3a8ea079b5393) like @nirinchev mentioned in https://github.com/realm/realm-dotnet/issues/2455#issuecomment-864267342 it fixes the problem.

Can you compare and try this against your code? @carbonete And if it does not work, provide us with more details about where and how your code is different / showing us a more extensive example?