3 ms·
You can do it with the type system, although in C# it is a bit clunky. For example let's say you have a class Resource that needs to be locked and a method Foo
by BazookaMusic 4y ago
You can do it with the type system, although in C# it is a bit clunky.
For example let's say you have a class Resource that needs to be locked and a method Foo(Resource) that needs to operate on the resource under a lock.
You could change Foo(Resource) to Foo(LockedResource). LockedResource could be a class that is defined using a lock object and a resource and takes the lock or validates that lock is taken in the constructor.
Then by making the object disposable the release can be handled as well.
This way the type system handles the validation.
This is kinda like a budget version of having the type system support locking and concurrency like Rust does.
- Akronymus 4y agoIn f# this would be even easier. (I wrote some capabilities based code before (for example, this part is only allowed read accesses to the DB)) When I tried something similar in c# I almost despaired.
- alkonaut 4y agoDisposable (unlike a Rust borrow) doesn’t give much in terms of guarantees though. You aren’t forced to dispose at method boundaries. But perhaps in C# you could use some locking token and make it one of the types that can’t leave the stack?