ReaderWriterLockSlim和异步\\的await [英] ReaderWriterLockSlim and async\await

查看:352
本文介绍了ReaderWriterLockSlim和异步\\的await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些问题 ReaderWriterLockSlim 。我不明白它是如何工作的魔法

I have some problems with ReaderWriterLockSlim. I cannot understand how it's magic working.

我的code:

 private async Task LoadIndex()
    {
        if (!File.Exists(FileName + ".index.txt"))
        {
            return;
        }
        _indexLock.EnterWriteLock();// <1>
        _index.Clear();
        using (TextReader index = File.OpenText(FileName + ".index.txt"))
        {
            string s;
            while (null != (s = await index.ReadLineAsync()))
            {
                var ss = s.Split(':');
                _index.Add(ss[0], Convert.ToInt64(ss[1]));
            }
        }
        _indexLock.ExitWriteLock();<2>
    }

当我在与下进写锁; 1>,调试器,我可以看到 _indexLock.IsWriteLockHeld 真正,但当执行步骤2>我看到 _indexLock.IsWriteLockHeld
_indexLock.ExitWriteLock 抛出异常 SynchronizationLockException 与消息写入锁没有被关押被释放。我做错了吗?

When I enter write lock at <1>, in debugger I can see that _indexLock.IsWriteLockHeld is true, but when execution steps to <2> I see _indexLock.IsWriteLockHeld is false and _indexLock.ExitWriteLock throws an exception SynchronizationLockException with message "The write lock is being released without being held". What I doing wrong?

推荐答案

ReaderWriterLockSlim 是一个线程仿射锁型,所以它通常不能与使用异步等待

ReaderWriterLockSlim is a thread-affine lock type, so it usually cannot be used with async and await.

您应该要么使用 SemaphoreSlim WaitAsync ,或者(如果你的真正的需要读/写器锁),用我的<一个href=\"http://nitoasyncex.$c$cplex.com/wikipage?title=AsyncReaderWriterLock&referringTitle=Documentation\"><$c$c>AsyncReaderWriterLock从AsyncEx 或斯蒂芬Toub的 AsyncReaderWriterLock

You should either use SemaphoreSlim with WaitAsync, or (if you really need a reader/writer lock), use my AsyncReaderWriterLock from AsyncEx or Stephen Toub's AsyncReaderWriterLock.

这篇关于ReaderWriterLockSlim和异步\\的await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆