views:

47

answers:

1
// Not thread-safe
class ShoppingCart {
    private List<Product> products;

    public void Add(Product p) { products.Add(p); }
    public void Remove(Product p) { products.Remove(p); }
}

Whenever user triggers an action associated with shopping cart, we pull it out and do what is needed.

// Could be a HTTP GET or AJAX pull
Add(Product product) {
    ShoppingCart cart = Session[User.ID];
    cart.Add(product);
}

My concern is that could the same user invoke multiple methods accessing the ShoppingCart causing dead-locks?

A: 

The question shouldn't be do in-memory objects limited to user/session scope need to be thread-safe but do I have multiple threads reading and writing to the same shared memory instance (no matter where it comes from)?

So if you never manually run some threads to do processing on this Session[User.ID] you don't need to synchronize it.

Darin Dimitrov