XandrUu
XandrUu

Reputation: 1179

How to lock a DataClass

I'm using a Linq to Sql connection to collaborate with a database and my windows form application works with multiple threads and this dosen't suite with the DataClass. I modify the connection to support MultipleActiveResultSets and I get this error "An item with the same key has already been added." I have searched for this problem and got only 2 answers:

I want to lock the DataClass and don't know where to lock it, I'm sure that some one used Linq to Sql in multithreading successfully.

Upvotes: 0

Views: 108

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064184

To expand on what I was saying in comments, and to answer your question - I would treat all access as a unit-of-work, for example (in some data-access class):

public Order GetOrder(int id) {
    // ctx could also be instantiated via an IoC/DI framework, etc
    using(var ctx = CreateDataContext()) {
        return ctx.Orders.SingleOrDefault(x => x.Id == id);
    }
}
public void AddOrder(Order order) {
    if(order == null) throw new ArgumentNullException("order");
    // ctx could also be instantiated via an IoC/DI framework, etc
    using(var ctx = CreateDataContext()) {
        ctx.Orders.InsertOnSubmit(order);
        ctx.SubmitChanges();
    }
}

etc. Key point: the data-context is not left open indefinitely and re-used by competing threads.

Upvotes: 2

Related Questions