一:ReaderWriteLock
从读写的角度进行功能分区
Sqllite:库锁
SqlServer:行锁【锁住行】
多个线程可以一起度,只能让一个线程去写。
读写是8/2开
读和写的时间如果时间比较长,都会影响他们。
static ReaderWriterLock reader = new ReaderWriterLock();
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Task.Factory.StartNew(() => {
Read();
});
}
Task.Factory.StartNew(() => {
Write();
});
Console.ReadKey();
}
/// <summary>
/// 线程读
/// </summary>
static void Read()
{
while (true)
{
Thread.Sleep(10);
reader.AcquireReaderLock(int.MaxValue);
Thread.Sleep(10);
Console.WriteLine("当前t={0}进行读取{1}",Thread.CurrentContext.ContextID,DateTime.Now);
reader.ReleaseReaderLock();
}
}
/// <summary>
/// 线程写
/// </summary>
static void Write()
{
while (true)
{
Thread.Sleep(3000);
reader.AcquireWriterLock(int.MaxValue);
Thread.Sleep(3000);
Console.WriteLine("当前t={0}进行写入........................................{1}", Thread.CurrentContext.ContextID,DateTime.Now);
reader.ReleaseWriterLock();
}
}
二:CountdownEvent
1 | static CountdownEvent countdown = new CountdownEvent(10); |
限制线程书的一个机制。
static CountdownEvent countdown = new CountdownEvent(10);
static void Main(string[] args)
{
countdown.Reset(10);
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(()=> {
LoadOrders();
});
}
countdown.Wait();
Console.WriteLine("所有Orders表执行完毕,恭喜!");
countdown.Reset(5);
for (int i = 0; i < 5; i++)
{
Task.Factory.StartNew(() => {
LoadProducts();
});
}
countdown.Wait();
Console.WriteLine("所有Products表执行完毕,恭喜!");
countdown.Reset(2);
for (int i = 0; i < 2; i++)
{
Task.Factory.StartNew(() => {
LoadUsers();
});
}
countdown.Wait();
Console.WriteLine("所有Users表执行完毕,恭喜!");
Console.WriteLine("所有的表执行完毕,恭喜!");
Console.ReadKey();
}
/// <summary>
/// 加载Order表
/// </summary>
static void LoadOrders()
{
//将当前的countdown减减操作
Console.WriteLine("当前Order正在加载中。。。{0}",Thread.CurrentThread.ManagedThreadId);
countdown.Signal();
}
/// <summary>
/// 加载Products表
/// </summary>
static void LoadProducts()
{
Console.WriteLine("当前Products正在加载中。。。{0}", Thread.CurrentThread.ManagedThreadId);
countdown.Signal();
}
/// <summary>
/// 加载Users表
/// </summary>
static void LoadUsers()
{
Console.WriteLine("当前Users正在加载中。。。{0}", Thread.CurrentThread.ManagedThreadId);
countdown.Signal();
}