勇哥注:
《多线程安全》这个系列会持续写下去,它是我的一个弱点,有兴趣的朋友可以选择性看看。
内核模式锁有三种:
事件锁AutoResetEvent,MuanualResetEventm,
信号量Semaphore,
互斥锁Mutex
这三种锁,我们发现都有一个WaitOne方法。。。因为他们都是继承于WaitHandle。
三种锁都是同根生,其实底层都是通过SafeWaitHandle来对win32api的一个引用。
在万不得已的情况下,不要使用内核模式的锁,因为代价太大。其实我们有更多的方式可以替代:混合锁机制, lock
先来谈谈AutoResetEvent
true:表示终止状态 false:表示非终止
现实中的场景: 进站火车闸机,我们用火车票来实现进站操作。
true: 终止表示: 闸机中没有火车票, 终止=> 初始状态
false: 非终止表示:闸机中此时有一张火车票
static AutoResetEvent areLock = new AutoResetEvent(false);
static void Main(string[] args)
{
areLock.WaitOne(); //塞一张火车票到闸机中,因为此时有票在闸机,所以我只能等待 =》 mainthread
Console.WriteLine("火车票检验通过,可以通行");
areLock.Set(); //从闸机中取火车票
}
WaitOne:用来将火车票塞入到闸机中 Set: 从闸机中把票取出来
static AutoResetEvent areLock = new AutoResetEvent(true);
static void Main(string[] args)
{
areLock.WaitOne(); //塞一张火车票到闸机中 =》 mainthread
Console.WriteLine("火车票检验通过,可以通行");
areLock.Set(); //从闸机中取火车票
}勇哥还举个栗子,这次它的目的是:
先执行a.show(), 完毕后再执行b.show()

源码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
AutoResetEvent auto = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
classA a = new classA();
classB b = new classB();
Task.Run(() =>
{
a.show();
auto.Set();
});
Task.Run(() =>
{
auto.WaitOne();
b.show();
auto.Set();
});
}
}
public class classA
{
public void show()
{
for (int i = 0; i < 5; i++)
{
int k = i;
var res=Task.Run(() =>
{
Console.WriteLine($"{i},{k},classAstart...[{Thread.CurrentThread.ManagedThreadId}]");
Thread.Sleep(1000);
Console.WriteLine($"{i},{k},classAend...[{Thread.CurrentThread.ManagedThreadId}]");
});
res.Wait();
}
}
}
public class classB
{
public void show()
{
for (int i = 0; i < 5; i++)
{
int k = i;
var res=Task.Run(() =>
{
Console.WriteLine($"{i},{k},classBstart...[{Thread.CurrentThread.ManagedThreadId}]");
Thread.Sleep(1000);
Console.WriteLine($"{i},{k},classBend...[{Thread.CurrentThread.ManagedThreadId}]");
});
res.Wait();
}
}
}
}---------------------
作者:hackpig
来源:www.skcircle.com
版权声明:本文为博主原创文章,转载请附上博文链接!