Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

6
  • 3
    +1 OP needs a class SelfReleasingMonitor: IDisposable which encapsulates the lockTaken value & the monitor. It has a static SelfReleasingMonitor TryEnter()" method which returns SelfReleasingMonitor, and an Exit method which calls monitor.Exit(I) if lockTaken is true. (it also sets locktaken to false). The Dispose method simply calls Exit (Exit can safely be called multiple times). Commented Oct 24, 2023 at 15:55
  • 4
    Note that the lock could also be managed this way. I actually did this for another project a few months ago that had concurrency issues. Looks like I'll be bringing it back here. Thank you. Commented Oct 24, 2023 at 16:07
  • As for purpose, yes, this method operates on a single retrieved value (a path to a .zip) pulled from a ConcurrentQueue. The method is run within a WinForms BackgroundWorker that's called every 30s by a Timer (supposedly disabling the Timer until completion). Even with a ConcurrentQueue, the lock may still be necessary though because the method operates on a specific set of prepared folders (separate from the ones deleted in the finally), and two iterations doing work on those folders at the same time would break the process. Commented Oct 24, 2023 at 16:17
  • 1
    @rdi_pck Sounds like a PeriodicTimer might be of use. The underlying timer is managed automatically, no need for manually starting and stopping, and there is no risk for concurrent iterations. Commented Oct 25, 2023 at 6:49
  • 1
    @rdi_pck I'm guessing you are using a Timers.Timer? If you use a Threading.Timer instead you can set it to trigger once only, and achieve much the same effect. You just need to reset it manually. Commented Oct 26, 2023 at 7:33