I would like to create a LINQ to SQL backed queue. However I am unsure how the best way to go about it is.
Right now I've done it something like this:
public static void Queue(Item item)
{
var db = new MyDataContext();
item.Time = DateTime.Now;
db.Items.InsertOnSubmit(item);
db.SubmitChanges();
}
public static Item TryDequeue()
{
try
{
var db = new MyDataContext();
var item = db.Items
.Where(x => x.Status == 0)
.OrderBy(x => x.Time)
.FirstOrDefault();
if (item == null)
return null;
item.Status += 1;
db.SubmitChanges();
return item;
}
catch (ChangeConflictException)
{
return null;
}
}
However, I do get some ChangeConflictException
s.
I was hoping the resulting query would be an atomic transaction that picks the element and sets it status and then returns, without any conflicts, thought that doesn't seem to be the case. I've tried using TransactionScope
but it complains about deadlocks.
What is the best way to go about achieving this?