C# release lock automatically after timeout

本秂侑毒 提交于 2019-12-13 12:33:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!