dotnet / dotnet/docs

Implementing Dispose Pattern: Thread Safety

Open
#39,770 0 comments 0 reactions 0 assignees View on GitHub
:watch: Not Triaged dotnet-fundamentals/svc
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.