What is the correct usage for sqlite on locking or async

前端 未结 2 1875
逝去的感伤
逝去的感伤 2021-02-06 14:15

We are using Xamarin to write C# code with SQLite for android and ios. However about how to use sqlite, I seem to have a conceptual misunderstanding:

What are the best p

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 15:13

    There's a big difference between synchronous vs asynchronous and single vs concurrent and there are all 4 combinations of them.

    In the single asynchronous case you access the DB using a single thread at most, but it doesn't need to be the same thread throughout the operation, and when you don't need a thread (when you are waiting for the IO operation to complete) you don't need any threads at all.

    The most basic way to limit the async usage to a single operation at a time is by using a SemaphoreSlim with initialCount = 1. A nicer way would be to use an AsyncLock (Building Async Coordination Primitives, Part 6: AsyncLock by Stephen Toub):

    private readonly AsyncLock _lock = new AsyncLock(); 
    
    public async Task InsertAsync (T item)
    {
        using(await _lock.LockAsync())
        {
            await asyncConnection.InsertAsync (item);
        }
    }
    
    public async Task InsertOrUpdateAsync (T item)
    {
        using(await _lock.LockAsync())
        {
            if (0 == await asyncConnection.UpdateAsync (item))
            {
                await asyncConnection.InsertAsync (item);
            }
        }
    }
    

    Note: My implementation of AsyncLock

提交回复
热议问题