Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[QUESTION] Should I keep the DB open during continuous INSERT operations? #2445

Open
alessandrofrancesconi opened this issue Mar 9, 2024 · 0 comments
Labels

Comments

@alessandrofrancesconi
Copy link

alessandrofrancesconi commented Mar 9, 2024

My application requires to continuously add data to a Collection, one time per second, for a theoretically infinite amount of time.

Each insertion is made by calling my method DatabaseOperations:Add(). Internally, it performs the following operations:

public class DatabaseOperations
{
  private LiteDatabase db;

  public void Add(SessionItem session, DataItem item) 
  {
    // 1: Get one item from a "Session" collection
    var collection = db.GetCollection<SessionItem>();
    var session = collection.Query().Where(s => s.Id == session.SourceDbId).FirstOrDefault();
    
    // 2: Get the Records collection (where the new data will be added)
    var records = db.GetCollection<DataItem>();
    item.Session = session; // assign the parent session to the item
    records.Insert(item);
  }
}

You see, db is the reference to the database and it is initialized at startup like this:

this.db = new LiteDatabase(this.GetDbPath());

Meaning, the referenced DB is always "open" during app lifecycle.
Considering that I will call Add() in a loop, one time per second, is it the correct way? Or should I discard the global reference and do this:

  public void Add(SessionItem session, DataItem item) 
  {
      using (var db = new LiteDatabase(this.GetDbPath()))  // use a local reference
      {
        // 1: Get one item from a "Session" collection
        var collection = db.GetCollection<SessionItem>();
        var session = collection.Query().Where(s => s.Id == session.SourceDbId).FirstOrDefault();
        
        // 2: Get the Records collection (where the new data will be added)
        var records = db.GetCollection<DataItem>();
        item.Session = session; // assign the parent session to the item
        records.Insert(item);
    }
  }

My only concern is that, this way, I will perform open/close operations at every iteration... isn't it too I/O intensive?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant