What is the correct usage for sqlite on locking or async

前端 未结 2 1821
逝去的感伤
逝去的感伤 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 14:57

    The fact that your Database doesn't accept multiple accesses (insertions, updates, etc..) doesn't mean that the single thread doing work against it has to do so using a blocking api.

    If you don't have to do cross-process locking, you can use SemaphoreSlim.WaitAsync instead of your Mutex inside your async method to await the lock asynchrnously:

    private readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(initialCount: 1);
    
    public async Task InsertAsync(T item)
    {
       await semaphoreSlim.WaitAsync();
       try
       {
          await asyncConnection.InsertAsync(item);
       }
       finally
       { 
          semaphoreSlim.Release();
       }
    }
    
    public async Task InsertOrUpdateAsync(T item)
    {
       await semaphoreSlim.WaitAsync();
       try
       {      
          int count = await asyncConnection.UpdateAsync(item);
          if (0 == count) 
          {
             await asyncConnection.InsertAsync(item);
          }
       }
       finally
       {
          semaphoreSlim.Release();
       }
    }
    

提交回复
热议问题