首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 多執行緒更新 WinForms 進度條完整範例

     編輯:關於C語言

背景

在子執行緒執行長時間工作(如下載),需安全更新 UI 進度條。

完整程式碼

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

namespace WindowsApplication4
{
    public partial class Form1 : Form
    {
        public Form1() { InitializeComponent(); }

        private void button1_Click(object sender, EventArgs e)
        {
            new Thread(new ThreadStart(StartDownload)).Start();
        }

        public void StartDownload()
        {
            Downloader downloader = new Downloader();
            downloader.onDownLoadProgress += downloader_onDownLoadProgress;
            downloader.Start();
        }

        void downloader_onDownLoadProgress(long total, long current)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Downloader.dDownloadProgress(downloader_onDownLoadProgress), total, current);
            }
            else
            {
                this.progressBar1.Maximum = (int)total;
                this.progressBar1.Value = (int)current;
            }
        }
    }

    public class Downloader
    {
        public delegate void dDownloadProgress(long total, long current);
        public event dDownloadProgress onDownLoadProgress;

        public void Start()
        {
            for (int i = 0; i < 100; i++)
            {
                if (onDownLoadProgress != null)
                    onDownLoadProgress(100, i);
                Thread.Sleep(100);
            }
        }
    }
}

關鍵點:使用 InvokeRequired 判斷是否需跨執行緒呼叫,透過 Invoke 將更新委派回 UI 執行緒。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved