1

I just trying to figuring out if it possible to implement locking mechanism inside class which inherited from the interface and injected with scoped lifetime. I would like to know, if lock mechanism have same thread lock behaviour mechanism as on singleton class or it's completely different? If so, in which direction I should move to achieve locking mechanism whether if it's possible for scoped objects.

For example, I've 2 requests which are trying to read data and cache it, for the first request I would like to block read method, read it's data, move it to cache and then release the lock and retrieve the response. For the 2nd request I would like read it from the cache instead of using another algorithm for reading data.

Maybe I've an wrong vision of how it's working, but as I understood, for the scoped objects, lock will be used only in the first request and would not block second request, am I right?

semper fi
  • 25
  • 4
  • 1
    You want to write something like `lock(this)` to lock? – Guru Stron Nov 22 '21 at 19:17
  • 1
    yes and moreover I would like to figure out, if 'lock(this)' would block for other requests for that class which injected throw dependency as `Scoped` – semper fi Nov 22 '21 at 19:47
  • 1
    Scoped in ASP DI means that the "service"'s lifetime lasts as long as the HTTP request. This means other requests get a different instance. And this means that locking with `lock` won't help to lock between two different instances. You could scope to Singleton or use a more elaborate mechanisms for syncing/locking. – lidqy Nov 22 '21 at 19:56
  • 1
    @semperfi no it will not. Also `lock(this)` usually is not a very good [design](https://stackoverflow.com/a/251668/2501279) choice. You can create an inner static field inside your object and use it for locking, but in general it is not a good idea also, I would say. So I would suggest to implement thread safe writes to cache somewhere outside the class itself. Like done in some answers [here](https://stackoverflow.com/questions/20149796/memorycache-thread-safety-is-locking-necessary). – Guru Stron Nov 22 '21 at 20:02
  • 1
    okay then, I was have good vision of it but anyway, is some techniques how it could be implemented the locking mechanism between request, or it's not possible at all? Without making the Singleton injection – semper fi Nov 22 '21 at 20:41

0 Answers0