使用.NET客户端进行RavenDB并发更新

时间:2012-05-15 16:48:43

标签: c# ravendb

我想知道使用.net客户端给出以下场景会发生什么。

using (IDocumentSession session = documentStore.OpenSession())
{
    thingToUpdate = session.Load<TUpdateThing>(id);

    // Modify thingToUpdate here

    // ** Someplace else the object is updated and saved. **

    session.SaveChanges();  // What happens here?
}

这是否会根据已更改的etag自动抛出错误,还是会关闭并覆盖其他人所做的更改?

我在http api上看到了一些与此相关的东西: http://ravendb.net/docs/http-api/http-api-comcurrency

1 个答案:

答案 0 :(得分:9)

你所说的是乐观并发。如果您想使用它,请设置

session.Advanced.UseOptimisticConcurrency = true;

默认情况下,未设置。

这是一个通过测试,证明了这一点:

public class ConcurrentUpdates : LocalClientTest
{
    [Fact]
    public void ConcurrentUpdatesWillThrowAConcurrencyException()
    {
        using (var store = NewDocumentStore())
        {
            var originalPost = new Post { Text = "Nothing yet" };
            using (var s = store.OpenSession())
            {
                s.Store(originalPost);
                s.SaveChanges();
            }

            using (var session1 = store.OpenSession())
            using (var session2 = store.OpenSession())
            {
                session1.Advanced.UseOptimisticConcurrency = true;
                session2.Advanced.UseOptimisticConcurrency = true;

                var post1 = session1.Load<Post>(originalPost.Id);
                var post2 = session2.Load<Post>(originalPost.Id);

                post1.Text = "First change";
                post2.Text = "Second change";

                session1.SaveChanges();

                // Saving the second text will throw a concurrency exception
                Assert.Throws<ConcurrencyException>(() => session2.SaveChanges());
            }

            using (var s = store.OpenSession())
            {
                Assert.Equal("First change", s.Load<Post>(originalPost.Id).Text);
            }
        }
    }

    public class Post
    {
        public string Id { get; set; }
        public string Text { get; set; }
    }
}