开发者

C# release lock automatically after timeout

开发者 https://www.devze.com 2023-02-15 03:22 出处:网络
does anyone have any ideas on whats the best way t开发者_C百科o implement a lock so that after X number of seconds it will automatically be released ?Assuming you are looking for an event to fire in X

does anyone have any ideas on whats the best way t开发者_C百科o implement a lock so that after X number of seconds it will automatically be released ?


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.


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);
    }
}


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


You could use TransactionScope with TransactionOptions timeout parameter.

using (TransactionScope tx = new TransactionScope(TransactionScopeOption.RequiresNew,
                    new TransactionOptions() { Timeout = new TimeSpan(0, 0, 10) }))

After the time ends, you will receive an TransactionAbortedException and the lock should be released.

It will be someting like this:

lock(_lock)
{
    try
    {
        using (TransactionScope tx = new TransactionScope(TransactionScopeOption.RequiresNew,
                        new TransactionOptions() { Timeout = new TimeSpan(0, 0, 10) }))
        {
            //do somenting important stuff
            tx.Complete();
            tx.Dispose();  // just remembering that will be disposed.
        }
    }
    catch (TransactionAbortedException tex)
    {
        throw new Exception("Operation Timeout");
    }
    catch (Exception)
    {
        throw; // do whatever you want
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消