Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the multi-threading issue at ClassFactory.GetDynamicClass #48

Merged
merged 3 commits into from Mar 29, 2016

Conversation

mobilebilly
Copy link
Contributor

The classes.Add(signature, type) is now placed within the writer lock, thus avoid multiple threads from updating the classes dictionary at the same time.

The issue is also mentioned here: http://stackoverflow.com/questions/7156181/system-linq-dynamic-selectnew-does-not-appear-to-be-thread-safe

The classes.Add(signature, type) is now placed within the writer lock, thus avoid multiple threads from updating the classes dictionary at the same time.
@ryanvgates
Copy link
Collaborator

@mobilebilly can you please create an issue for this issue? And reference this pull request?

@ryanvgates
Copy link
Collaborator

@mobilebilly Can you please add unit tests that demonstrate the issue?

@mobilebilly
Copy link
Contributor Author

@ryanvgates I wish I could. But it is not possible to create unit test cases to reproduce multi thread race condition issues.

@mobilebilly
Copy link
Contributor Author

@ryanvgates The unit test is added, I am able to reproduce the problem most of them time with that.

@ryanvgates
Copy link
Collaborator

@mobilebilly Why did you go the caching route rather than using ConcurrentDictionary like in the first answer http://stackoverflow.com/a/23956017/299327?

@mobilebilly
Copy link
Contributor Author

Hi @ryanvgates, that could be a possible solution, but not an ideal one due to the following reasons.

  1. the ConcurrentDictionary.GetOrAdd call is not atomic (http://stackoverflow.com/questions/10486579/concurrentdictionary-pitfall-are-delegates-factories-from-getoradd-and-addorup), meaning that the CreateDynamicClass (which is a very expensive call due to code emit) can still be called more than once under race condition for a single dynamic type.
  2. When CreateDynamicClass is being called more than once, a single dynamic type will result of multiple emissions . All of the emitted types will be added to module.Assembly.DefinedTypes. The extra copies are never used, but they will never be released until the process is terminated.

A better solution is to enforce thread safety with reader/writer lock, so that we can ensure CreateDynamicClass is called only once per dynamic type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants