1

我必须实现一些涉及由不同线程访问的共享资源的.Net 代码。原则上,这应该通过简单的读写锁来解决。但是,我的解决方案要求某些读取访问最终会产生写入操作。我首先检查了ReaderWriterLockSlim,但它本身并不能解决问题,因为它要求我提前知道读操作是否可以变成写操作,而这不是我的情况。我最终选择了简单地使用 ReaderWriterLockSlim,当读取操作“检测到”需要执行写入操作时,释放读取锁并获取写入锁。我不确定是否有更好的解决方案,或者该解决方案是否会导致一些同步问题(我有 Java 经验,但我对 .Net 相当陌生)。

下面的一些示例代码说明了我的解决方案:

public class MyClass
{
    private int[] data;

    private readonly ReaderWriterLockSlim syncLock = new ReaderWriterLockSlim();

    public void modifyData()
    {
        try
        {
            syncLock.EnterWriteLock();

            // clear my array and read from database...
        }
        finally
        {
            syncLock.ExitWriteLock();
        }
    }

    public int readData(int index)
    {
        try
        {
            syncLock.EnterReadLock();
            // some initial preprocessing of the arguments

            try
            {
                _syncLock.ExitReadLock();
                _syncLock.EnterWriteLock();

                // check if a write is needed <--- this operation is fast, and, in most cases, the result will be false
                // if true, perform the write operation
            }
            finally
            {
                _syncLock.ExitWriteLock();
                _syncLock.EnterReadLock();
            }

            return data[index];
        }
        finally
        {
            syncLock.ExitReadLock();
        }
    }

}
4

0 回答 0