问题
does anyone have any ideas on whats the best way to implement a lock so that after X number of seconds it will automatically be released ?
回答1:
In web development, I cache all the time with a sliding timeout. Perhaps you could use a cached object as the lock?
Here's a discussion of caching technologies in non-web applications:
Caching in C# without System.Web
回答2:
Assuming you are looking for an event to fire in X seconds, then I don't think there's any core Mutex object which currently provides the type of functionality you are looking for.
You could create this type of functionality by using a System.Timer (to fire in X seconds and release a locked Mutex) or by using a thread which Sleep's for X seconds - I'd prefer the first method.
However, both of these will be scheduled within the user/application layer - so you would have to wait for them to be scheduled.
回答3:
You can achieve this using Monitor.TryEnter
. Please refer below -
Synchronization problems with Monitor class in WCF service
if(Monitor.TryEnter(lockObj, timeout)) {
try {
...
} finally {
Monitor.Exit(lockObj);
}
}
来源:https://stackoverflow.com/questions/5222658/c-sharp-release-lock-automatically-after-timeout