[點晴永久免費OA]C#多線程的啟動與停止
當前位置:點晴教程→點晴OA辦公管理信息系統
→『 經驗分享&問題答疑 』
using System; using System.Threading; using System.Windows.Forms; using EastWestWalk.NetFrameWork.Redis; namespace Producer { public partial class FrmMain : Form { private static string queueid = "MqId001";//隊列id private static bool IsStrat = false;//是否繼續生產信息 private Thread StartThread = null;//生產線程 private static bool IsEnd = false;//是否繼續消費信息 private Thread EndThread = null;//消費線程 public FrmMain() { InitializeComponent(); } /// <summary> ///開始生產按鈕事件 /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void btn_start_Click(object sender, EventArgs e) { if (btn_start.Text == "開始生產") { IsStrat = true; StartThread = new Thread(EnqueueRun); StartThread.Start(); btn_start.Text = "正在生產"; } else { IsStrat = false; Thread.Sleep(50);//這里很重要 不然線程任務還沒結束 會報錯 if (StartThread != null && StartThread.ThreadState == ThreadState.Running) { StartThread.Abort(); StartThread = null; } btn_start.Text = "開始生產"; } } /// <summary> ///開始消費按鈕事件 /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void btn_end_Click(object sender, EventArgs e) { if (btn_end.Text == "開始消費") { IsEnd = true; EndThread = new Thread(DequeueRun); EndThread.Start(); btn_end.Text = "正在消費"; } else { IsEnd = false; Thread.Sleep(50); if (EndThread != null && EndThread.ThreadState == ThreadState.Running) { EndThread.Abort(); EndThread = null; } btn_end.Text = "開始消費"; } } /// <summary> /// 批量生產 /// </summary> private void EnqueueRun() { using (var client = new DoRedisString(RedisUtility.RedisConfig)) { int i = 0; while (IsStrat) { string str = i + DateTime.Now.Ticks.ToString(); client.Core.EnqueueItemOnList(queueid, str); txt_log.BeginInvoke(new Action(() => { txt_log.AppendText($"生產:{str}\n"); txt_log.selectionStart = txt_log.TextLength; txt_log.ScrollToCaret(); })); i++; Thread.Sleep(20); } } } /// <summary> ///批量消費 /// </summary> private void DequeueRun() { using (var client = new DoRedisString(RedisUtility.RedisConfig)) { while (IsEnd) { if (client.Core.GetListCount(queueid) > 0) { string result = client.Core.DequeueItemfromList(queueid); txt_log.BeginInvoke(new Action(() => { txt_log.AppendText($"消費:{result}\n"); txt_log.selectionStart = txt_log.TextLength; txt_log.ScrollToCaret(); })); RedisUtility.SetRedis(result, $"消費成功:{result}", DateTime.Now.AddSeconds(30)); Thread.Sleep(20); } else { //如果當前隊列為空,掛起1s Thread.Sleep(1000); client.Core.EnqueueItemOnList(queueid, "0"); } } } } } } txt_log.BeginInvoke(new Action(() => { txt_log.AppendText($"消費:{result}\n"); txt_log.selectionStart = txt_log.TextLength; txt_log.ScrollToCaret(); })); 該文章在 2022/11/25 15:18:02 編輯過 |
關鍵字查詢
相關文章
正在查詢... |