Advertisement
GeorgePashev_88

Untitled

Oct 31st, 2023
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. public sealed class DatabaseManager
  2. {
  3. private static readonly Lazy<DatabaseManager> lazyInstance = new Lazy<DatabaseManager>(() => new DatabaseManager());
  4. private readonly Queue<DatabaseCommand> commandQueue = new Queue<DatabaseCommand>();
  5. private readonly Thread executorThread;
  6. private readonly string connectionString = "Data Source=sample.db;Version=3;";
  7.  
  8. private DatabaseManager()
  9. {
  10. executorThread = new Thread(ExecuteCommands);
  11. executorThread.Start();
  12. }
  13.  
  14. public static DatabaseManager Instance => lazyInstance.Value;
  15.  
  16. public void EnqueueCommand(DatabaseCommand command)
  17. {
  18. lock (commandQueue)
  19. {
  20. commandQueue.Enqueue(command);
  21. Monitor.Pulse(commandQueue);
  22. }
  23. }
  24.  
  25. private void ExecuteCommands()
  26. {
  27. while (true)
  28. {
  29. DatabaseCommand command = null;
  30. lock (commandQueue)
  31. {
  32. while (commandQueue.Count == 0)
  33. {
  34. Monitor.Wait(commandQueue);
  35. }
  36. command = commandQueue.Dequeue();
  37. }
  38.  
  39. using (var connection = new SQLiteConnection(connectionString))
  40. {
  41. connection.Open();
  42. command.Execute(connection);
  43. }
  44. }
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement