10

我想在原子操作中进行检查然后更新。我正在使用 dbcontext 来管理事务。如果记录已被另一个线程修改但没有引发异常,我希望得到一个异常。任何帮助,将不胜感激。这是我的输出:

Thread-4: Reading...
Thread-5: Reading...
Thread-5: Updating destination 1
Thread-4: Updating destination 1
Thread-4: SaveChanges
Thread-5: SaveChanges

这是我的代码片段:

public static void Main(string[] args)
{
    PopulateData();
    (new Thread(UpdateDestination1)).Start();
    (new Thread(UpdateDestination1)).Start();
}

public static void UpdateDestination1()
{
    using (var context1 = new BreakAwayContext())
    {
        Console.WriteLine("Thread-{0}: Reading...", Thread.CurrentThread.ManagedThreadId);
        var d = context1.Destinations.FirstOrDefault();
        Console.WriteLine("Thread-{0}: Updating destination {1}", Thread.CurrentThread.ManagedThreadId, d.DestinationId);
        d.Name = "Thread-" + Thread.CurrentThread.ManagedThreadId;
        try
        {
            context1.SaveChanges();
            Console.WriteLine("Thread-{0}: SaveChanges", Thread.CurrentThread.ManagedThreadId);
        }
        catch (OptimisticConcurrencyException)
        {
            Console.WriteLine("OptimisticConcurrencyException!!!");
            throw;
        }
    }
}
4

1 回答 1

18

在使用流式 API ( http: //msdn.aspx ) 或 IsConcurrencyToken() 或 .IsRowversion 配置属性时,您可以在属性 ( http://msdn.microsoft.com/en-us/data/gg193958.aspx ) 或microsoft.com/en-us/data/jj591617#1.12)。通常,您将在数据库中有一个 rowversion 列。

于 2012-10-25T03:32:51.620 回答