Skip to content

"Database is locked" when multiple threads and BeginTransaction (Sqlite) #9994

@marcova84

Description

@marcova84

When I call the method shown below from different threads (3 or more), I immediately get a "Database is locked" error:

Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 5: 'database is locked'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()

Steps to reproduce

Run the following method from 3 or more threads:

public void Run()
        {
            while (true)
            {
                var cs = "Data Source=sandbox.db";

                using (var con = new SqliteConnection(cs))
                {
                    con.Open();

                    using (var tr = con.BeginTransaction())
                    {
                        using (var cmd = con.CreateCommand())
                        {
                            cmd.CommandText = "SELECT Value FROM SandboxItems ORDER BY SandboxItemId DESC LIMIT 1";
                            var currentValue = Convert.ToInt32(cmd.ExecuteScalar());

                            currentValue++;

                            cmd.CommandText = $"INSERT INTO SandboxItems(Name, Value) VALUES ('Sandbox item {DateTime.Now:HH: mm: ss yyyy:MM: dd}', '{currentValue}')";
                            
                            cmd.ExecuteNonQuery();
                        }

                        tr.Commit();
                    }

                    con.Close();
                }

                Thread.Sleep(150);
            }
        }

Further technical details

EF Core version: Microsoft.EntityFrameworkCore.Sqlite (2.0.0)
Database Provider: Microsoft.Data.Sqlite.Core (2.0.0)
Operating system: Windows 10 Pro
IDE: (Visual Studio 2017)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions