Recursive AI

Is SQLite async in C#?

Microsoft.Data.Sqlite runs async methods synchronously.

Microsoft.Data.Sqlite’s async methods run synchronously because native SQLite doesn’t expose asynchronous I/O.

OneLite is a free, open-source SQLite-compatible database for .NET from Recursive AI, licensed MIT or Apache-2.0. NuGet · GitHub

dotnet add package RecursiveAI.OneLite.Data --version 1.0.0

On a local .db file, awaiting OneLite.Data frees the calling thread only if the storage operation actually has to wait asynchronously; cached reads and I/O that runs inline don’t yield.

In a .NET 10 console project, run this against a new async-demo.db file:

Program.cs.NET 10
using RecursiveAI.OneLite.Data;
 
await using var db = new OneLiteConnection("Data Source=async-demo.db");
await db.OpenAsync();
await using var query = db.CreateCommand();
query.CommandText = "CREATE TABLE IF NOT EXISTS demo(n INTEGER);";
await query.ExecuteNonQueryAsync();
query.CommandText = "SELECT count(*) FROM demo";
Console.WriteLine($"Rows: {await query.ExecuteScalarAsync()}");
OutputText
Rows: 0

A storage wait you can see

A VFS (virtual file system) is the layer OneLite uses to read and write database files; here it reads over HTTP.

Replace Program.cs with the following. The in-process HTTP handler holds the database response until you release it, so no network or server is needed.

Program.cs.NET 10
using System.Net;
using System.Net.Http.Headers;
using RecursiveAI.OneLite.Data;
using RecursiveAI.OneLite.Storage.Vfs;
 
var path = Path.GetTempFileName();
byte[] bytes;
try
{
    using (var seed = new OneLiteConnection($"Data Source={path}"))
    {
        seed.Open();
        using var insert = seed.CreateCommand();
        insert.CommandText = "CREATE TABLE t(n); INSERT INTO t VALUES (42);";
        insert.ExecuteNonQuery();
    }
    bytes = File.ReadAllBytes(path);
}
finally { File.Delete(path); }
 
var handler = new GatedStorage(bytes);
using var http = new HttpClient(handler);
OneLiteConnection.RegisterVfs("demo", new HttpRangeVfs(http));
await using var db = new OneLiteConnection(
    "Data Source=https://example.invalid/demo.db;Mode=ReadOnly;Vfs=demo");
var opening = db.OpenAsync();
Console.WriteLine($"Open complete before response: {opening.IsCompleted}");
handler.Release.SetResult();
await opening;
 
await using var read = db.CreateCommand();
read.CommandText = "SELECT n FROM t";
await read.ExecuteScalarAsync(); // Warm the query path.
var cached = read.ExecuteScalarAsync();
Console.WriteLine($"Warm query complete on return: {cached.IsCompleted}");
Console.WriteLine($"Value: {await cached}");
 
sealed class GatedStorage(byte[] bytes) : HttpMessageHandler
{
    public TaskCompletionSource Release { get; } =
        new(TaskCreationOptions.RunContinuationsAsynchronously);
 
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken token)
    {
        if (request.Method == HttpMethod.Head)
            return new HttpResponseMessage(request.RequestUri!.AbsolutePath.EndsWith("/demo.db", StringComparison.Ordinal)
                ? HttpStatusCode.OK : HttpStatusCode.NotFound);
 
        await Release.Task.WaitAsync(token);
        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(bytes)
        };
        response.Headers.ETag = new EntityTagHeaderValue("\"demo-v1\"");
        return response;
    }
}
OutputText
Open complete before response: False
Warm query complete on return: True
Value: 42

An async method can complete synchronously

In Microsoft.Data.Sqlite, using ExecuteReaderAsync instead of ExecuteReader doesn’t free the calling thread while native SQLite reads a page. The provider runs the operation synchronously. Moving that work to Task.Run can keep a UI thread responsive, but it still occupies a worker thread while the operation blocks.

In OneLite.Data 1.0.0, an async call can suspend when the backend returns an incomplete operation. The sample holds open a storage wait deliberately; it does not time a disk read. Once the pages needed by the query are cached, there may be no storage wait at all. An IsCompleted value of True on the warm query is expected. It doesn’t mean the provider wraps all its calls in synchronous I/O.

Which calls can suspend depends on the storage backend and operation. Browser storage or HTTP can leave a thread free while a request is pending; a backend that serves a call inline leaves nothing to await. Async does not make the disk itself read any faster. SQL execution and materializing rows still take CPU time.

Cancellation is for the I/O wait

Pass a CancellationToken to the OneLite async command or reader method. OneLite observes it at I/O waits and throws OperationCanceledException when a query’s pending wait is canceled; the connection stays usable. Don’t treat the token as a deadline for a fully cached query: it may finish without reaching a cancellation point. DbCommand.Cancel() is a no-op in this provider. Async cancellation · Command behavior

WAL changes reader and writer overlap, not async I/O

SQLite’s write-ahead logging mode lets a reader keep its snapshot while a writer appends to the log. Native SQLite still allows only one writer at a time, and WAL doesn’t make Microsoft.Data.Sqlite’s methods nonblocking. Use WAL to address reader–writer contention; use async storage to free the calling thread during a storage wait.

In OneLite, the optional BEGIN CONCURRENT write path is available through the engine or Database API, not through OneLite.Data. An async command doesn’t opt into concurrent writes, and a OneLite connection isn’t thread-safe. For connection setup and commands, see the OneLite ADO.NET guide; for transaction overlap, see WAL vs. rollback journal.