[点晴永久免费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 编辑过 |
关键字查询
相关文章
正在查询... |