C# 异步进度条

这篇博客介绍了如何在C# Winform应用中实现异步进度条,包括主窗体、进度条窗体的设计代码,以及使用BackgroundWorker组件进行异步操作,确保在后台处理任务时更新UI。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


在别的地方看到的代码,主要为自己使用方便。转贴。没有别人,只有自己。没有你需要的,只有我需要的。 可是我需要的,正是你需要的。 -----本Blog只方便于本人工作和学习编程而设立,所以只进行本人所需技术文章保存用,且全为转贴。 连这个公告也是转的,来自http://blog.youkuaiyun.com/johncools/哈哈哈哈哈哈
转载!!!!!!
https://www.cnblogs.com/Deckard/archive/2009/06/24/1510454.html
以上为原地址

C# winform进度条(异步) 窗体设计代码
主窗体:

namespace BackgroudWokerUI
{
partial class MainForm
{
///
/// Required designer variable.
///
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.listBox1 = new System.Windows.Forms.ListBox();
        this.listBox2 = new System.Windows.Forms.ListBox();
        this.moveButton = new System.Windows.Forms.Button();
        this.addButton = new System.Windows.Forms.Button();
        this.textBox = new System.Windows.Forms.TextBox();
        this.label = new System.Windows.Forms.Label();
        this.cancelButton = new System.Windows.Forms.Button();
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.moveBackButton = new System.Windows.Forms.Button();
        this.SuspendLayout();
        //
        // listBox1
        //
        this.listBox1.FormattingEnabled = true;
        this.listBox1.ItemHeight = 12;
        this.listBox1.Location = new System.Drawing.Point(49, 44);
        this.listBox1.Name = "listBox1";
        this.listBox1.Size = new System.Drawing.Size(120, 148);
        this.listBox1.TabIndex = 0;
        //
        // listBox2
        //
        this.listBox2.FormattingEnabled = true;
        this.listBox2.ItemHeight = 12;
        this.listBox2.Location = new System.Drawing.Point(224, 44);
        this.listBox2.Name = "listBox2";
        this.listBox2.Size = new System.Drawing.Size(120, 148);
        this.listBox2.TabIndex = 1;
        //
        // moveButton
        //
        this.moveButton.Location = new System.Drawing.Point(186, 247);
        this.moveButton.Name = "moveButton";
        this.moveButton.Size = new System.Drawing.Size(70, 26);
        this.moveButton.TabIndex = 2;
        this.moveButton.Text = "Move";
        this.moveButton.Click += new System.EventHandler(this.moveButton_Click);
        //
        // addButton
        //
        this.addButton.Location = new System.Drawing.Point(94, 247);
        this.addButton.Name = "addButton";
        this.addButton.Size = new System.Drawing.Size(75, 23);
        this.addButton.TabIndex = 5;
        this.addButton.Text = "Add";
        this.addButton.Click += new System.EventHandler(this.addButton_Click);
        //
        // textBox
        //
        this.textBox.Location = new System.Drawing.Point(49, 220);
        this.textBox.Name = "textBox";
        this.textBox.Size = new System.Drawing.Size(120, 21);
        this.textBox.TabIndex = 6;
        //
        // label
        //
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(272, 220);
        this.label.Name = "label";
        this.label.Size = new System.Drawing.Size(0, 0);
        this.label.TabIndex = 7;
        //
        // cancelButton
        //
        this.cancelButton.Location = new System.Drawing.Point(274, 296);
        this.cancelButton.Name = "cancelButton";
        this.cancelButton.Size = new System.Drawing.Size(70, 26);
        this.cancelButton.TabIndex = 8;
        this.cancelButton.Text = "Cancel";
        this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
        //
        // label1
        //
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(47, 9);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(28, 12);
        this.label1.TabIndex = 9;
        this.label1.Text = "From";
        //
        // label2
        //
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(222, 9);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(16, 12);
        this.label2.TabIndex = 10;
        this.label2.Text = "To";
        //
        // moveBackButton
        //
        this.moveBackButton.Location = new System.Drawing.Point(274, 247);
        this.moveBackButton.Name = "moveBackButton";
        this.moveBackButton.Size = new System.Drawing.Size(70, 26);
        this.moveBackButton.TabIndex = 11;
        this.moveBackButton.Text = "MoveBack";
        this.moveBackButton.Click += new System.EventHandler(this.moveBackButton_Click);
        //
        // MainForm
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(386, 359);
        this.Controls.Add(this.moveBackButton);
        this.Controls.Add(this.label2);
        this.Controls.Add(this.label1);
        this.Controls.Add(this.cancelButton);
        this.Controls.Add(this.label);
        this.Controls.Add(this.textBox);
        this.Controls.Add(this.addButton);
        this.Controls.Add(this.moveButton);
        this.Controls.Add(this.listBox2);
        this.Controls.Add(this.listBox1);
        this.Name = "MainForm";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "idior.cnblogs.com";
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.ListBox listBox2;
    private System.Windows.Forms.Button moveButton;
    private System.Windows.Forms.Button addButton;
    private System.Windows.Forms.TextBox textBox;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.Button cancelButton;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Button moveBackButton;
}

}

进度条窗体:

//===============================================================================
// Microsoft patterns & practices
// CompositeUI Application Block
//===============================================================================
// Copyright ?Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED “AS IS” WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================

namespace BackgroudWokerUI
{
partial class ProgressForm
{
///
/// Required designer variable.
///
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.progressWork = new System.Windows.Forms.ProgressBar();
        this.SuspendLayout();
        //
        // progressWork
        //
        this.progressWork.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                    | System.Windows.Forms.AnchorStyles.Right)));
        this.progressWork.Location = new System.Drawing.Point(12, 11);
        this.progressWork.Name = "progressWork";
        this.progressWork.Size = new System.Drawing.Size(221, 21);
        this.progressWork.TabIndex = 0;
        //
        // ProgressForm
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(245, 43);
        this.Controls.Add(this.progressWork);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        this.Name = "ProgressForm";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "ProgressForm";
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.ProgressBar progressWork;
}

}

进度条页面:

//===============================================================================
// Microsoft patterns & practices
// CompositeUI Application Block
//===============================================================================
// Copyright ?Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED “AS IS” WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BackgroudWokerUI
{
public partial class ProgressForm : Form
{
public ProgressForm()
{
InitializeComponent();
}

    //工作完成后执行的事件
    public void OnProcessCompleted(object sender, EventArgs e)
    {
        this.Close();
    }

    //工作中执行进度更新
    public void OnProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressWork.Value = e.ProgressPercentage;
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
}

}

主页面:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

//Note You must be careful not to manipulate any user-interface objects
//in your System.ComponentModel.BackgroundWorker.DoWork event handler.
//Instead, communicate to the user interface through the
//System.ComponentModel.BackgroundWorker.ProgressChanged and
//System.ComponentModel.BackgroundWorker.RunWorkerCompleted events.

namespace BackgroudWokerUI
{
public partial class MainForm : Form
{
//BindingList is useful list for UI
private IList leftList = new BindingList();
private IList rightList = new BindingList();

    private BackgroundWorker worker = null;

    public MainForm()
    {
        InitializeComponent();
        //Databinding here
        listBox1.DataSource = leftList;
        listBox2.DataSource = rightList;
    }

    private void addButton_Click(object sender, EventArgs e)
    {
        if (textBox.Text.Length != 0)
        {
            leftList.Add(textBox.Text);
            textBox.Text = "";
            textBox.Focus();
        }
    }

    private void moveButton_Click(object sender, EventArgs e)
    {
        //显示进度条
        ProgressForm progressForm = new ProgressForm();
        progressForm.Show();

        // Prepare the background worker for asynchronous prime number calculation
        //准备进度条的记数
        worker= new BackgroundWorker();
        // Specify that the background worker provides progress notifications 
        //指定提供进度通知
        worker.WorkerReportsProgress = true;
        // Specify that the background worker supports cancellation
        //提供中断功能
        worker.WorkerSupportsCancellation = true;
        // The DoWork event handler is the main work function of the background thread
        //线程的主要功能是处理事件
        //开启线程执行工作
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        // Specify the function to use to handle progress
        //指定使用的功能来处理进度
        worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        worker.ProgressChanged += new ProgressChangedEventHandler(progressForm.OnProgressChanged);
        // Specify the function to run when the background worker finishes
        // There are three conditions possible that should be handled in this function:
        // 1. The work completed successfully
        // 2. The work aborted with errors
        // 3. The user cancelled the process
        //进度条结束完成工作
        //
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值