Implementing Dispose Pattern: Thread Safety
- Dominant language
- No language data
- Stars
- 4.8k
- Forks
- 6.1k
- Avg merge
- 19h 10m
- Merged PRs (30d)
- 268
Description
### Type of issue
Missing information
### Description
I have a class that interacted with native c++ code. On Construction, it creates a c++ object dynamically with new and saves a pointer to it as IntPtr. To free the unmanaged ressource, in this case the heap allocated c++ object, I implemented the dispose pattern as suggested and call a c++ method that calls delete on the object pointer in the disposing: false path.
To my suprise, I was hit by a double free error, although all dispose calls come from the same thread. After investigating for a while, it turned out, that finalize and dispose can both be invoked at the same time, bypassing the if (!_disposedValue) check. I fixed the issue by using int as type for _disposedValue Interlocked.Exchange(...) in the if statement.
I suggest adding information about thread safety in the documentation page
### Page URL
https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose
### Content source URL
https://github.com/dotnet/docs/blob/main/docs/standard/garbage-collection/implementing-dispose.md
### Document Version Independent Id
9c754da1-c234-fb12-580b-0fcf9ffe2c20
### Article author
@gewarren
### Metadata
* ID: 572ef6c6-5066-4a14-76a0-c3fb4b62e604
* Service: **dotnet-fundamentals**
Contributor guide
Assessment
This issue has not been assessed yet.