C # base: Ejemplo 2 - hilo barra de progreso de control de rodadura (hilos añadidos)

C # base: Ejemplo 2 - hilo barra de progreso de control de rodadura (hilos añadidos)

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

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false; // 使线程可以调用窗体控件
        }
        public Thread th1, th2;
        public void TestProcess1()
        {
            int count = 0;                          // 标识合适加载线程2
            while (true)
            {                               
                pgBar1.PerformStep();               // 设置进度条的当前值
                count += pgBar1.Step;               // 标识每步增加固定步长
                Thread.Sleep(200);                   // 使线程1休眠50ms
                if (count == 20)                    //当count=20时,添加线程2任务
                {
                    th2.Join();
                }
            }
        }
        public void TestProcess2()
        {
            int count = 0;
            while (true)
            {
                pgBar2.PerformStep();
                count += pgBar2.Step;
                Thread.Sleep(200);
                if (count == 200)
                    break;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 如果关闭窗口时,线程还在运行则终止
            if (th1.ThreadState == ThreadState.Running)
                th1.Abort();
            if (th2.ThreadState == ThreadState.Running)
                th2.Abort();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            th1 = new Thread(new ThreadStart(TestProcess1));
            th1.Start();
            th2 = new Thread(new ThreadStart(TestProcess2));
            th2.Start();
        }
    }
}


salida:
Aquí Insertar imagen Descripción

Publicado 38 artículos originales · ganado elogios 29 · Vistas a 50000 +

Supongo que te gusta

Origin blog.csdn.net/ruotianxia/article/details/105160563
Recomendado
Clasificación