本文介绍了你将如何简化了进入和退出ReaderWriterLock?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这似乎很嘈杂的我。五大行的开销实在太多了。
This seems very noisy to me. Five lines of overhead is just too much.
m_Lock.EnterReadLock()
Try
Return m_List.Count
Finally
m_Lock.ExitReadLock()
End Try
所以,你会怎么简单吗?
So how would you simply this?
推荐答案
我的想法一样,但在C#;-p
I was thinking the same, but in C# ;-p
using System;
using System.Threading;
class Program
{
static void Main()
{
ReaderWriterLockSlim sync = new ReaderWriterLockSlim();
using (sync.Read())
{
// etc
}
}
}
public static class ReaderWriterExt
{
sealed class ReadLockToken : IDisposable
{
private ReaderWriterLockSlim sync;
public ReadLockToken(ReaderWriterLockSlim sync)
{
this.sync = sync;
sync.EnterReadLock();
}
public void Dispose()
{
if (sync != null)
{
sync.ExitReadLock();
sync = null;
}
}
}
public static IDisposable Read(this ReaderWriterLockSlim obj)
{
return new ReadLockToken(obj);
}
}
这篇关于你将如何简化了进入和退出ReaderWriterLock?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!