为建立中文知识库加块砖 ——中科大胡不归
0. 前言
第一次在技术群提出这个问题,大佬们一脸懵逼,既然你要串行执行,为什么不单线程。其实就是由于很多场景需要封装的业务逻辑,并依赖线程,比如顺序写日志文件。
当然这是我现阶段粗浅水平所能想到的实现方法,希望以后能接触到更广大的世界,能嘲笑今天的自己。
1. 实现原理
AutoResetEvent
依赖AutoResetEvent的信号机制实现“串行”。
对象方法:
- Set表示设置为有信号状态,这时调用WaitOne的线程将继续执行;
- Reset表示设置为无信号状态,这时调用WaitOne的线程将阻塞;
- WaitOne表示在无信号状态时阻塞当前线程,也就是说WaitOne只有在无信号状态下才会阻塞线程。
因为AutoResetEvent调用Set后会在第一个调用WaitOne后,自动将信号置为无信号状态,导致其他调用WaitOne的线程继续阻塞。
Queue
使用Queue的“先进先出”特性实现“顺序”。
最早使用ThreadPool,但是不能控制线程顺序被唤醒。也可能是未得其法,希望有大神看到能指正用法。
2. 代码
正文只贴关键代码:
1public partial class MainWindow 2 { 3 private readonly Queue<CookieTask> _threadQueue = new Queue<CookieTask>(); 4 private readonly AutoResetEvent _autoResetEvent = new AutoResetEvent(true); 5 private int _count = 10; 6 7 public MainWindow() 8 { 9 InitializeComponent(); 10 11 var task = new Thread(SerialService); 12 task.Start(); 13 } 14 15 private void SerialService() 16 { 17 while (true) 18 { 19 if (_threadQueue.Count > 0) 20 { 21 var tt = _threadQueue.Dequeue(); 22 tt.Worker.Start(tt.Data); 23 } 24 25 Thread.Sleep(500); 26 } 27 } 28 29 private void Button_OnClick(object sender, RoutedEventArgs e) 30 { 31 for (var i = 0; i < 100; i++) 32 { 33 var tt1 = new Thread(DemoTask); 34 _threadQueue.Enqueue(new CookieTask(tt1, _count--)); 35 if (_count <= 0) 36 { 37 _count = 10; 38 } 39 } 40 } 41 42 private void DemoTask(object seconds) 43 { 44 _autoResetEvent.WaitOne(); 45 46 int times = int.Parse(seconds.ToString()); 47 while (times-- > 0) 48 { 49 Debug.Write(int.Parse(seconds.ToString()) + " "); 50 Thread.Sleep(10); 51 } 52 Debug.WriteLine(""); 53 54 _autoResetEvent.Set(); 55 } 56 }
完整工程
我们在初始化AutoResetEvent对象时,将初始为true即表示有信号状态,所以第一个提交的DemoTask中的WaitOne能拿到信号。
AutoResetEvent在第一个调用WaitOne后,自动将信号置为无信号状态导致其他调用WaitOne阻塞。