简体   繁体   English

在C#中实现锁定的设计模式

[英]Design pattern to implement Locking in C#

My code looks something like : 我的代码看起来像:

private string TryOperation(Some parameters)
{
    using (var guard = new OperationGuardWithCleanup(params)) // Aquire lock
    {
        if (guard.TryStartOperation())
        {
            Operation(otherParams); // Actual operation method
            return "Success"
        }
        else
        {
            return "false";
        }
    }
}

I want to provide implementation the functionality that could take arbitrary "Operation". 我想提供实现可能需要任意“操作”的功能。 Is there a recommended design pattern for such utility. 是否有针对此类实用程序的推荐设计模式。

Here is one simplistic way you could implement it, which you should test and harden for your own purposes. 这是实现它的一种简单方法,应该针对自己的目的进行测试和强化。 You should think about what you are trying to achieve because this will synchronize all operations across your process which might not be what you want. 您应该考虑要实现的目标,因为这将使整个过程中的所有操作同步化,而这可能并不是您想要的。

private string TryOperation(Action operation)
{
    using (var guard = new OperationGuardWithCleanup())
    {
        if (guard.TryStartOperation())
        {
            operation();
            return "Success";
        }
        else
        {
            return "false";
        }
    }
}

public class OperationGuardWithCleanup : IDisposable
{
    private bool disposedValue = false;
    private static readonly object _operationLock = new object();

    public OperationGuardWithCleanup()
    {
        Monitor.Enter(_operationLock);
    }

    public bool TryStartOperation()
    {
        // ?
        return true;
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                Monitor.Exit(_operationLock);
            }

            disposedValue = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
    }
}

If I understand your question, then using a delegate (similar to a function pointer in C++) would likely meet your needs. 如果我理解您的问题,那么使用委托(类似于C ++中的函数指针)可能会满足您的需求。

The "Action" type can be a good choice of delegates. “动作”类型可以是代表的不错选择。

private string TryOperation(Some parameters, Action<OtherParamsType> operation)
{
    using (var guard = new OperationGuardWithCleanup(params))
    {
        if (guard.TryStartOperation())
        {
            operation(otherParams); // Actual operation method
            return "Success"
        }
        else
        {
            return "false";
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM