c#如何在while循环中填充进度条

本文关键字:填充 循环 while | 更新日期: 2023-09-27 18:10:23

我试图在while循环中填充我的ProgressBar。但不知何故,进度条的值不会增长。

我想要的代码打开一个文本文件,并张贴每一行在它的请求。

我的代码:

public void registerAccounts()
{
    const Int32 BufferSize = 128;
    using (var fileStream = File.OpenRead(nsTextBox3.Text))
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
    {
        String line;
        while ((line = streamReader.ReadLine()) != null)
        {
            var request = (HttpWebRequest)WebRequest.Create("http://registration.zwinky.com/registration/register.jhtml");
            var postData = "form=reg&success=http://profile.zwinky.com/zwinkyprofile/main.jhtml?username=&tp=&user.partnerId=ZZzer000&source=zwinky&design=classic&ad=/&user.userName=" + line + "&user.password=" + nsTextBox1.Text + "&user.passwordConfirm=" + nsTextBox1.Text + "&user.secretQId=1&user.secretQAnswer=" + line + "&user.birthdayMonth=1&user.birthdayDay=1&user.birthdayYear=1996&user.gender=M&user.emailAddr=" + nsTextBox2.Text + "&emailAddrConfirm=" + nsTextBox2.Text + "&x=42&y=51&partnerCode=/";
            var data = Encoding.ASCII.GetBytes(postData);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        }
    }
}

我该如何让我的GUI中的进度条现在增长?

我考虑像这样计算文本文档中的行数:

var lineCount = File.ReadLines(nsTextBox3.Text).Count();

,然后在其中运行for循环。但它不会可悲地成长。

感谢您的帮助。

c#如何在while循环中填充进度条

您似乎正在应用程序的UI线程上运行此方法。这个线程负责更新UI,所以当它忙于循环时,它不能这样做。可能发生的情况是,一旦循环完成,进度条会直接更新为100%,而你看不到它。

看看如何使用后台工作器。

它通过以一种非常简单的方式为您完成所有的线程和回调来处理上述问题。

直接取自MSDN文章的例子:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace SL_BackgroundWorker_CS
{
    public partial class Page : UserControl
    {
        private BackgroundWorker bw = new BackgroundWorker();
        public Page()
        {
            InitializeComponent();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }
        private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
        }
        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            if (bw.WorkerSupportsCancellation == true)
            {
                bw.CancelAsync();
            }
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 1; (i <= 10); i++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress((i * 10));
                }
            }
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                this.tbProgress.Text = "Canceled!";
            }
            else if (!(e.Error == null))
            {
                this.tbProgress.Text = ("Error: " + e.Error.Message);
            }
            else
            {
                this.tbProgress.Text = "Done!";
            }
        }
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
        }
    }
}

将循环放在DoWork中,进度条放在ProgressChanged中。简单的!

你可以试试这个,这个是不完美的,但工作

int linecount=0;
while ((line = streamReader.ReadLine()) != null)
{
linecount=linecount+1;
}
int number=0;
while ((line = streamReader.ReadLine()) != null)
 {
number=number+1;
    // what is yor work
progressBar1.Value = i * progressBar1.Maximum / linecount;  //show process bar counts
LabelTotal.Text = i.ToString() + " of " + linecount; //show number of count in lable
int presentage = (i * 100) / linecount;
LabelPresentage.Text = presentage.ToString() + " %"; //show precentage in lable
Application.DoEvents(); //keep form active in every loop 
}