如何根据在列表视图/列表中的条目删除和停止线程?

时间:2019-04-02 22:05:32

标签: c# multithreading forms

我有一些代码,每次单击按钮时都会启动一个新线程。每个新线程在原始图形引擎中的随机位置绘制一个随机着色的圆,并将其添加到Listview。指向此引擎的链接为https://github.com/NAIT-CNT/GDIDrawer

我需要找到一种基于用户单击的Listview项来删除和中止线程的方法。

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;
using GDIDrawer;
using System.Threading;

namespace ica7
{
    public partial class Form1 : Form
    {
        CDrawer _gdi = new CDrawer();
        List<Thread> _threads = new List<Thread>();
        Random _rng = new Random();
        Point _coords;
        int _diameter;
        bool _isRunning;

        public Form1()
        {
            InitializeComponent();
            _diameter = 10;
            _isRunning = true;
            btnStopThreads.Enabled = false;
        }


        private Color RandomColor()
        {
            return Color.FromArgb(_rng.Next(256), _rng.Next(256), _rng.Next(256));
        }

        private void DrawCircle(int diameter, Point coords, CDrawer gdi)
        {
            gdi.AddCenteredEllipse(coords, diameter, diameter, RandomColor());
        }

        private void btnStartThread_Click(object sender, EventArgs e)
        {
            btnStopThreads.Enabled = true;
            Thread t = new Thread(() =>
            {
                int diameter = _diameter;
                while (_isRunning)
                {
                    _coords.X = _rng.Next(800);
                    _coords.Y = _rng.Next(600);
                    DrawCircle(diameter, _coords, _gdi);
                    Thread.Sleep(10);
                }
            });
            _threads.Add(t);
            ListViewItem lvi = new ListViewItem(t.ToString());
            lboxThreads.Items.Add(lvi);
            t.Start();
        }

        private void btnStopThreads_Click(object sender, EventArgs e)
        {
            _threads.ElementAt(lboxThreads.SelectedIndex).Abort();
            lboxThreads.Items.RemoveAt(lboxThreads.SelectedIndex);

        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            _diameter = trackBar1.Value;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            _threads.ForEach(x => x.Abort());
        }
    }
}

这是设计器文件,以备需要时使用:

namespace ica7
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.btnStartThread = new System.Windows.Forms.Button();
            this.btnStopThreads = new System.Windows.Forms.Button();
            this.lboxThreads = new System.Windows.Forms.ListBox();
            this.trackBar1 = new System.Windows.Forms.TrackBar();
            this.lblTbMin = new System.Windows.Forms.Label();
            this.lblTbMax = new System.Windows.Forms.Label();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
            this.SuspendLayout();
            // 
            // btnStartThread
            // 
            this.btnStartThread.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
            this.btnStartThread.Location = new System.Drawing.Point(9, 11);
            this.btnStartThread.Name = "btnStartThread";
            this.btnStartThread.Size = new System.Drawing.Size(121, 23);
            this.btnStartThread.TabIndex = 0;
            this.btnStartThread.Text = "Start a Thread";
            this.btnStartThread.UseVisualStyleBackColor = true;
            this.btnStartThread.Click += new System.EventHandler(this.btnStartThread_Click);
            // 
            // btnStopThreads
            // 
            this.btnStopThreads.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
            this.btnStopThreads.Location = new System.Drawing.Point(9, 40);
            this.btnStopThreads.Name = "btnStopThreads";
            this.btnStopThreads.Size = new System.Drawing.Size(121, 23);
            this.btnStopThreads.TabIndex = 1;
            this.btnStopThreads.Text = "Stop Selected Thread";
            this.btnStopThreads.UseVisualStyleBackColor = true;
            this.btnStopThreads.Click += new System.EventHandler(this.btnStopThreads_Click);
            // 
            // lboxThreads
            // 
            this.lboxThreads.FormattingEnabled = true;
            this.lboxThreads.Location = new System.Drawing.Point(138, 11);
            this.lboxThreads.Name = "lboxThreads";
            this.lboxThreads.Size = new System.Drawing.Size(303, 134);
            this.lboxThreads.TabIndex = 2;
            // 
            // trackBar1
            // 
            this.trackBar1.Location = new System.Drawing.Point(9, 69);
            this.trackBar1.Maximum = 50;
            this.trackBar1.Minimum = 10;
            this.trackBar1.Name = "trackBar1";
            this.trackBar1.Size = new System.Drawing.Size(121, 45);
            this.trackBar1.TabIndex = 3;
            this.trackBar1.Value = 10;
            this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
            // 
            // lblTbMin
            // 
            this.lblTbMin.AutoSize = true;
            this.lblTbMin.Location = new System.Drawing.Point(6, 101);
            this.lblTbMin.Name = "lblTbMin";
            this.lblTbMin.Size = new System.Drawing.Size(19, 13);
            this.lblTbMin.TabIndex = 4;
            this.lblTbMin.Text = "10";
            // 
            // lblTbMax
            // 
            this.lblTbMax.AutoSize = true;
            this.lblTbMax.Location = new System.Drawing.Point(111, 101);
            this.lblTbMax.Name = "lblTbMax";
            this.lblTbMax.Size = new System.Drawing.Size(19, 13);
            this.lblTbMax.TabIndex = 5;
            this.lblTbMax.Text = "50";
            // 
            // timer1
            // 
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
            this.ClientSize = new System.Drawing.Size(453, 157);
            this.Controls.Add(this.lblTbMax);
            this.Controls.Add(this.lblTbMin);
            this.Controls.Add(this.trackBar1);
            this.Controls.Add(this.lboxThreads);
            this.Controls.Add(this.btnStopThreads);
            this.Controls.Add(this.btnStartThread);
            this.ForeColor = System.Drawing.SystemColors.ActiveCaption;
            this.Name = "Form1";
            this.Text = "Form1";
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnStartThread;
        private System.Windows.Forms.Button btnStopThreads;
        private System.Windows.Forms.ListBox lboxThreads;
        private System.Windows.Forms.TrackBar trackBar1;
        private System.Windows.Forms.Label lblTbMin;
        private System.Windows.Forms.Label lblTbMax;
        private System.Windows.Forms.Timer timer1;
    }
}

如果有任何更好的方法可以做到这一点,请告诉我。这是我第一次尝试线程。这是作业。

0 个答案:

没有答案