3 ms·
The one that caught me recently was assuming that you could use a Dictionary as a concurrent cache. You can't. Dictionary can be read concurrently, but once y
by Pxtl 10y ago
The one that caught me recently was assuming that you could use a Dictionary as a concurrent cache.
You can't. Dictionary can be read concurrently, but once you start writing to it concurrently all bets are off. ConcurrentDictionary implements IDictionary and allows concurrent writes.
Also, Entity Framework. We had an icky bug coming from somebody storing the datacontext in a member variable. Don't do that.
- cm2187 10y agoThe one I am concerned about is iterators (for each). I have read somewhere that iterators are stateful and I should be careful when using them in a multi-threaded environment. Currently I am ignoring this advice and use them happily (on static lists and dictionaries) but I am not sure if this isn't going to bite me some day. But I don't understand how it would bite me.
- jdmichal 10y agoThat is because your different threads are not using the same `Enumerator`. I'm guessing your threads look something like this, based on your mention of `foreach`: // In multiple threads: foreach(element in collection) { ... } `collection` is not an `Enumerator` but rather an `Enumerable`. The `foreach` statement calls `collection.GetEnumerator`, so each thread gets its own iterator. You would only see inconsistencies if another thread modified the collection during iteration. Try this instead, and you'll guaranteed see issues: // Before: IEnumerator enumerator = collection.getEnumerator(); // In multiple threads: while(enumerator.Move()) { var element = enumerator.Current; }
- tracker1 10y agoYou want ConcurrentDictionary[1]... the worst one I saw was attaching information keyed off the thread id. Note: in ASP.Net lifecycle there are no guarantees that two events (load, prerender, render, etc) will be performed on the same thread from the pool. Wound up seeing some REALLY weird issues... HttpContext.Current.Items is your friend there. https://msdn.microsoft.com/en-us/library/dd287191(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/dd287191(v=vs.110)....