C# release lock automatically after timeout

本小妞迷上赌 提交于 2019-12-06 09:46:50
Josh Pearce

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

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.

Kumar

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