Running insert on one thread and delete on another throws exception
Hi David, I am not sure if I am using LiteDB correctly but I wanna use it as a simple persisted cache in my desktop .NET 4.5 windows service app. I will be adding records from one thread and then I will run another thread which will select all records and then process them in the application and then delete from the cache. I tried this scenario with LiteDB but I am getting random exceptions in different part of the code.
The exceptions are as follows and they are appearing randomly:
- Invalid transaction on top of stack
- Unable to cast object of type 'LiteDB.HeaderPage' to type 'LiteDB.CollectionPage'.
- This transaction is cancelled due to an aborted transaction
- Unable to cast object of type 'LiteDB.CollectionPage' to type 'LiteDB.HeaderPage'.
Here is the example:
using System;
using System.Threading;
using System.Threading.Tasks;
using LiteDB;
namespace ConsoleApplication2
{ // Create your POCO class
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string[] Phones { get; set; }
public bool IsActive { get; set; }
}
class Program
{
public static LiteDatabase _db;
static void Main(string[] args)
{
using (var db = new LiteDatabase(@"C:\Temp\MyData.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<Customer>("customers");
Task.Factory.StartNew(() =>
{
while (true)
{
var customer = new Customer
{
Name = "John Doe",
Phones = new string[] { "8000-0000", "9000-0000" },
IsActive = true
};
// Insert new customer document (Id will be auto-incremented)
col.Insert(customer);
}
});
Task.Factory.StartNew(() =>
{
while (true)
{
var results = col.FindAll();
foreach (var customer in results)
{
col.Delete(customer.Id);
}
}
});
Thread.Sleep(TimeSpan.FromHours(1));
}
}
}
}
I guess I have some issue with the code or maybe I didnt understand purpose of LiteDb so please let me know how to fix it. Thanks, Jan
Hi, LiteDB v1/v2 are not safe thread. If you want use you must lock statment (read and write operations).
Current v3-beta supports multi-thread and my dev branch will support multi-process too.
Hi David, thanks for the reply. I didnt realise that I am using version 2. I will get version 3 and test it. Thanks, Jan