using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic; public class SynchronizedCache
{
private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
private Dictionary<int, string> innerCache = new Dictionary<int, string>(); public int Count
{ get { return innerCache.Count; } } public string Read(int key)
{
cacheLock.EnterReadLock();
try
{
return innerCache[key];
}
finally
{
cacheLock.ExitReadLock();
}
} public void Add(int key, string value)
{
cacheLock.EnterWriteLock();
try
{
innerCache.Add(key, value);
}
finally
{
cacheLock.ExitWriteLock();
}
} public bool AddWithTimeout(int key, string value, int timeout)
{
if (cacheLock.TryEnterWriteLock(timeout))
{
try
{
innerCache.Add(key, value);
}
finally
{
cacheLock.ExitWriteLock();
}
return true;
}
else
{
return false;
}
} public AddOrUpdateStatus AddOrUpdate(int key, string value)
{
cacheLock.EnterUpgradeableReadLock();
try
{
string result = null;
if (innerCache.TryGetValue(key, out result))
{
if (result == value)
{
return AddOrUpdateStatus.Unchanged;
}
else
{
cacheLock.EnterWriteLock();
try
{
innerCache[key] = value;
}
finally
{
cacheLock.ExitWriteLock();
}
return AddOrUpdateStatus.Updated;
}
}
else
{
cacheLock.EnterWriteLock();
try
{
innerCache.Add(key, value);
}
finally
{
cacheLock.ExitWriteLock();
}
return AddOrUpdateStatus.Added;
}
}
finally
{
cacheLock.ExitUpgradeableReadLock();
}
} public void Delete(int key)
{
cacheLock.EnterWriteLock();
try
{
innerCache.Remove(key);
}
finally
{
cacheLock.ExitWriteLock();
}
} public enum AddOrUpdateStatus
{
Added,
Updated,
Unchanged
}; ~SynchronizedCache()
{
if (cacheLock != null) cacheLock.Dispose();
}
}
 using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic; public class Example
{
public static void Main()
{
var sc = new SynchronizedCache();
var tasks = new List<Task>();
int itemsWritten = ; // Execute a writer.
tasks.Add(Task.Run( () => { String[] vegetables = { "broccoli", "cauliflower",
"carrot", "sorrel", "baby turnip",
"beet", "brussel sprout",
"cabbage", "plantain",
"spinach", "grape leaves",
"lime leaves", "corn",
"radish", "cucumber",
"raddichio", "lima beans" };
for (int ctr = ; ctr <= vegetables.Length; ctr++)
sc.Add(ctr, vegetables[ctr - ]); itemsWritten = vegetables.Length;
Console.WriteLine("Task {0} wrote {1} items\n",
Task.CurrentId, itemsWritten);
} ));
// Execute two readers, one to read from first to last and the second from last to first.
for (int ctr = ; ctr <= ; ctr++) {
bool desc = Convert.ToBoolean(ctr);
tasks.Add(Task.Run( () => { int start, last, step;
int items;
do {
String output = String.Empty;
items = sc.Count;
if (! desc) {
start = ;
step = ;
last = items;
}
else {
start = items;
step = -;
last = ;
} for (int index = start; desc ? index >= last : index <= last; index += step)
output += String.Format("[{0}] ", sc.Read(index)); Console.WriteLine("Task {0} read {1} items: {2}\n",
Task.CurrentId, items, output);
} while (items < itemsWritten | itemsWritten == );
} ));
}
// Execute a red/update task.
tasks.Add(Task.Run( () => { Thread.Sleep();
for (int ctr = ; ctr <= sc.Count; ctr++) {
String value = sc.Read(ctr);
if (value == "cucumber")
if (sc.AddOrUpdate(ctr, "green bean") != SynchronizedCache.AddOrUpdateStatus.Unchanged)
Console.WriteLine("Changed 'cucumber' to 'green bean'");
}
} )); // Wait for all three tasks to complete.
Task.WaitAll(tasks.ToArray()); // Display the final contents of the cache.
Console.WriteLine();
Console.WriteLine("Values in synchronized cache: ");
for (int ctr = ; ctr <= sc.Count; ctr++)
Console.WriteLine(" {0}: {1}", ctr, sc.Read(ctr)); }
}
// The example displays the following output:
// Task 1 read 0 items:
//
// Task 3 wrote 17 items
//
//
// Task 1 read 17 items: [broccoli] [cauliflower] [carrot] [sorrel] [baby turnip] [
// beet] [brussel sprout] [cabbage] [plantain] [spinach] [grape leaves] [lime leave
// s] [corn] [radish] [cucumber] [raddichio] [lima beans]
//
// Task 2 read 0 items:
//
// Task 2 read 17 items: [lima beans] [raddichio] [cucumber] [radish] [corn] [lime
// leaves] [grape leaves] [spinach] [plantain] [cabbage] [brussel sprout] [beet] [b
// aby turnip] [sorrel] [carrot] [cauliflower] [broccoli]
//
// Changed 'cucumber' to 'green bean'
//
// Values in synchronized cache:
// 1: broccoli
// 2: cauliflower
// 3: carrot
// 4: sorrel
// 5: baby turnip
// 6: beet
// 7: brussel sprout
// 8: cabbage
// 9: plantain
// 10: spinach
// 11: grape leaves
// 12: lime leaves
// 13: corn
// 14: radish
// 15: green bean
// 16: raddichio
// 17: lima beans

构造函数

ReaderWriterLockSlim()

使用默认属性值初始化 ReaderWriterLockSlim 类的新实例。

ReaderWriterLockSlim(LockRecursionPolicy)

在指定锁定递归策略的情况下初始化 ReaderWriterLockSlim 类的新实例。

属性

CurrentReadCount

获取已进入读取模式锁定状态的独有线程的总数。

IsReadLockHeld

获取一个值,该值指示当前线程是否已进入读取模式的锁定状态。

IsUpgradeableReadLockHeld

获取一个值,该值指示当前线程是否已进入可升级模式的锁定状态。

IsWriteLockHeld

获取一个值,该值指示当前线程是否已进入写入模式的锁定状态。

RecursionPolicy

获取一个值,该值指示当前 ReaderWriterLockSlim 对象的递归策略。

RecursiveReadCount

获取当前线程进入读取模式锁定状态的次数,用于指示递归。

RecursiveUpgradeCount

获取当前线程进入可升级模式锁定状态的次数,用于指示递归。

RecursiveWriteCount

获取当前线程进入写入模式锁定状态的次数,用于指示递归。

WaitingReadCount

获取等待进入读取模式锁定状态的线程总数。

WaitingUpgradeCount

获取等待进入可升级模式锁定状态的线程总数。

WaitingWriteCount

获取等待进入写入模式锁定状态的线程总数。

方法

Dispose()

释放 ReaderWriterLockSlim 类的当前实例所使用的所有资源。

EnterReadLock()

尝试进入读取模式锁定状态。

EnterUpgradeableReadLock()

尝试进入可升级模式锁定状态。

EnterWriteLock()

尝试进入写入模式锁定状态。

Equals(Object)

确定指定的对象是否等于当前对象。

(Inherited from Object)

ExitReadLock()

减少读取模式的递归计数,并在生成的计数为 0(零)时退出读取模式。

ExitUpgradeableReadLock()

减少可升级模式的递归计数,并在生成的计数为 0(零)时退出可升级模式。

ExitWriteLock()

减少写入模式的递归计数,并在生成的计数为 0(零)时退出写入模式。

GetHashCode()

作为默认哈希函数。

(Inherited from Object)

GetType()

获取当前实例的 Type

(Inherited from Object)

MemberwiseClone()

创建当前 Object 的浅表副本。

(Inherited from Object)

ToString()

返回表示当前对象的字符串。

(Inherited from Object)

TryEnterReadLock(Int32)

尝试进入读取模式锁定状态,可以选择整数超时时间。

TryEnterReadLock(TimeSpan)

尝试进入读取模式锁定状态,可以选择超时时间。

TryEnterUpgradeableReadLock(Int32)

尝试进入可升级模式锁定状态,可以选择超时时间。

TryEnterUpgradeableReadLock(TimeSpan)

尝试进入可升级模式锁定状态,可以选择超时时间。

TryEnterWriteLock(Int32)

尝试进入写入模式锁定状态,可以选择超时时间。

TryEnterWriteLock(TimeSpan)

尝试进入写入模式锁定状态,可以选择超时时间。

C# System.Threading.ReaderWriterLockSlim的更多相关文章

  1. c# System.Threading.Thread

    using System; using System.Threading; // Simple threading scenario: Start a static method running // ...

  2. .Net多线程编程—System.Threading.Tasks.Parallel

    System.Threading.Tasks.Parallel类提供了Parallel.Invoke,Parallel.For,Parallel.ForEach这三个静态方法. 1 Parallel. ...

  3. System.Threading.Timer 定时器的用法

    System.Threading.Timer 是C# 中的一个定时器,可以定时(不断循环)执行一个任务.它是在线程上执行的,具有很好的安全性.为此  .Net Framework 提供了5个重载的构造 ...

  4. C# System.Threading.Timer 使用方法

    public class TimerHelper { System.Threading.Timer timer; public TaskSendMMS tasksendmms { get; set; ...

  5. C#中的线程四(System.Threading.Thread)

    C#中的线程四(System.Threading.Thread) 1.最简单的多线程调用 System.Threading.Thread类构造方法接受一个ThreadStart委托,改委托不带参数,无 ...

  6. C#错误之 System.Threading.ThreadAbortException:正在中止线程

    参考:http://www.cnblogs.com/chendaoyin/archive/2013/06/27/3159211.html 1.开启一个子线程 //开启一个子线程,子线程调用方法 Met ...

  7. System.Threading.Timer使用心得

    System.Threading.Timer 是一个使用回调方法的计时器,而且由线程池线程服务,简单且对资源要求不高. "只要在使用 Timer,就必须保留对它的引用."对于任何托 ...

  8. “System.Threading.ThreadAbortException”类型的第一次机会异常在 mscorlib.dll 中发

    问题原因: Thread.Abort 方法 .NET Framework 4  其他版本   1(共 1)对本文的评价是有帮助 - 评价此主题 在调用此方法的线程上引发 ThreadAbortExce ...

  9. System.Threading.ThreadAbortException: 正在中止线程。

    在 System.Threading.ThreadAbortException 中第一次偶然出现的"mscorlib.dll"类型的异常 "System.Threadin ...

随机推荐

  1. python 全栈开发,Day60(MySQL的前戏,数据库概述,MySQL安装和基本管理,初识MySQL语句)

    一.MySQL的前戏 在学习Mysql之前,我们先来想一下一开始做的登录注册案例,当时我们把用户的信息保存到一个文件中: #用户名 |密码 root|123321 alex|123123 上面文件内容 ...

  2. DDD领域模型查询方法实现(八)

    在DDD.Domain工程文件夹Repository下创建RequestPage类: public class RequestPage { public RequestPage(int pagesiz ...

  3. Mysql在master上查看有哪些slave

    mysql> select * from information_schema.processlist as p where p.command = 'Binlog Dump'; 或 mysql ...

  4. google gcr.io、k8s.gcr.io 国内镜像

    1.首先添加docker官方的国内镜像 sudo tee /etc/docker/daemon.json <<-'EOF' { "registry-mirrors": ...

  5. python导包踩过的坑之包名和模块名同名

  6. 李宏毅机器学习笔记2:Gradient Descent(附带详细的原理推导过程)

    李宏毅老师的机器学习课程和吴恩达老师的机器学习课程都是都是ML和DL非常好的入门资料,在YouTube.网易云课堂.B站都能观看到相应的课程视频,接下来这一系列的博客我都将记录老师上课的笔记以及自己对 ...

  7. 洛谷.2219.[HAOI2007]修筑绿化带(单调队列)

    题目链接 洛谷 COGS.24 对于大的矩阵可以枚举:对于小的矩阵,需要在满足条件的区域求一个矩形和的最小值 预处理S2[i][j]表示以(i,j)为右下角的C\(*\)D的矩阵和, 然后对于求矩形区 ...

  8. 2041 ACM 超级楼梯

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=2041 数学问题,找规律,可以先假设全一步,然后一个两步的,两个两步的~~.很容易发现规律:F[N]=F[N ...

  9. Codeforces 932G Palindrome Partition 回文树+DP

    题意:给定一个串,把串分为偶数段 假设分为$s_1,s_2,s_3....s_k$ 求满足$ s_1=s_k,s_2=s_{ k-1 }... $的方案数模$10^9+7$ $|S|\leq 10^6 ...

  10. Android native thread相关

    几个主要的source code路径: /system/core/include/utils/threads.h /system/core/include/utils/Thread.h /system ...