Thread Security for Hashtable in LogicalCallContext

When using LogicalCallContext to exchange some data on streams, we encountered an exception from the following stack trace

 System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.Collections.Hashtable.HashtableEnumerator.MoveNext() at System.Runtime.Remoting.Messaging.LogicalCallContext.Merge(LogicalCallContext lc) at System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message reqMsg, Boolean bProxyCase) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed, MessageData& msgData) 

I read from MSDN when EndInvoke called CallContext merges in streams. My question is not about CallContext inside CallContext concurrency support. If this is not supported, should we use CallContext at the first point? If yes, then there are some recommendations for this.

Can someone explain when I can see this stack trace?

an example for such a scenario is more useful if you can share.

+7
multithreading c #
source share
2 answers

CallContext works by creating a copy of the current collection on a remote computer, and then merging back the changes made to that copy during the call. This is what he tries to do when he throws this exception. It seems you passed the context to another thread that modifies the collection while the structure copies the changes. The exception you see is that a particular collection is not thread safe, but even if it uses a thread safe collection, there will be a race condition - changes made to the collection after copying the changes will be lost. Before ending the call, you need to make all the changes in your context.

+2
source share

If you can change the Hashtable , you might consider replacing it with the ConcurrentDictionary<TKey, TValue> . Adding and removing items in this class is completely thread safe and may solve your problem.

This is a thread safe alternative to the Dictionary class, so you still have your own collection of key values.

Learn more about ConcurrentDictionary here on MSDN.

-one
source share