并发编程尝试
网上搜到很多理论,没有实际的例子,自己尝试写一写
.Net Framework 4.5
VS 2017
WinForm 项目
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Win.Order.Thread { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //跨线程调用控件检查=取消 CheckForIllegalCrossThreadCalls = false; } private async void button1_Click(object sender, EventArgs e) { var num = int.Parse(textBox1.Text); await Task.Run(() => { StringBuilder sb = new StringBuilder(); //多线程并发,乱序执行 Parallel.For(0, num, (i) => { var api = new Api(); string str = api.OrderAction(i); sb.AppendLine(str); }); //放到上面循环里会卡死,就放到外面了 richTextBox1.AppendText(sb.ToString()); //滚动条滚到最底部 richTextBox1.ScrollToCaret(); }); } private void button2_Click(object sender, EventArgs e) { richTextBox1.Clear(); } } public class Api { //唯一记录(来一个记录一个,不移除) public static System.Collections.Concurrent.ConcurrentQueue<int> list1 = new System.Collections.Concurrent.ConcurrentQueue<int>(); //处理中(拿一个,少一个 static System.Collections.Concurrent.ConcurrentQueue<int> list2 = new System.Collections.Concurrent.ConcurrentQueue<int>(); //处理完成(完成一个记录一个) static System.Collections.Concurrent.ConcurrentQueue<int> list3 = new System.Collections.Concurrent.ConcurrentQueue<int>(); static object lockObj = new object(); static bool IsExecuting = false; public string OrderAction(int id) { if (list3.Contains(id)) { return $"{id}已处理完成,不要重复提交"; } if (list2.Contains(id)) // { return $"{id}已加入排队处理1"; } if (list1.Contains(id)) { } else { list1.Enqueue(id); list2.Enqueue(id); } if (IsExecuting && !list2.Contains(id) && !list3.Contains(id)) { return $"{id}正在处理"; } if (IsExecuting) { return $"{id}已加入排队处理2"; } lock (lockObj) { if (IsExecuting) { return $"{id}已加入排队处理3"; } else { IsExecuting = true; //一个一个执行 Task.Run(() => { //IsExecuting = true; //多个一起执行 while (list2.TryDequeue(out int first)) { System.Threading.Thread.Sleep(5000); list3.Enqueue(first); } IsExecuting = false; }); return $"{id}已加入排队处理4"; } } } } }