LINQ to SQL的 - 队列队列、LINQ、to、SQL

2023-09-06 16:54:42 作者:守不住的空城

我想创建一个的LINQ to SQL支持队列。但是我不知道该如何去了解它的最好办法就是。

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;
    }
}

不过,我得到一些 ChangeConflictException 秒。

我希望得到的查询将是挑选的元素,并将其设置状态,然后返回,没有任何冲突的原子事务,认为似乎并不如此。我已经尝试过使用的TransactionScope 但抱怨死锁。

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?

推荐答案

您可以继续使用的并发性问题做这个

You could continue with the concurrency issue by doing this

db.SubmitChanges(ConflictMode.ContinueOnConflict);

但请理解它的陷阱。