ValueType disposable scope
Is there a safe way to use a value type to manage a disposable "scope"? For example in this code, it should write "1" to the console, but it actually writes "2" because it creates a copy of
scope1
and disposes it:
24 Replies
It's writing
2
because disposeCount
is a global static fieldI get that yeah
This would also happen with a class, for example
For a class it would only write 1
Since it swaps out
myObject
for null when disposedtrue! Missed that
I'm just curious if there's a way to use a value type instead of a class since it's a somewhat hot path in my app
Is a copy of the struct a valid case in your app?
Nah
kk
Just trying to get a more optimal solution I guess?
I guess i can just use Enter/Exit scope methods but then I have to use try finally everywhere
What are you doing with the object btw? That info may also help
It's to batch together multiple changes into a single operation
Where each change by itself would trigger an expensive update, instead i can batch multiple changes
The the dispose is supposed to perform the single operation?
kk, I like the pattern
If there's no other scopes also undisposed then yes
it uses a counter
It kinda reminds me of the
ILogger<T>
interface from Microsoft
Idk if the source of that is available but you might wanna take a lookThey must use a class too since it returns IDisposable
oh well
i forgot you can make protected methods in an interface, I might try out something with that
you are calling Dispose twice there
Yes
no my bad
it should work as is, why
ref struct
?I just copied the idea from the Lock class, i can't remember what it does except for disallow the value as a field in a non-ref struct
ref struct is useful when you need to group a bunch of
ref T
to something
allows you to pass it around and refs remain valid
you can use an array like a stack and use a ref to the top of the stack
not safe at all but..Ship it