我有以下代码读取文件,并在阅读时增加te进度条,但我在progressBar
中没有看到任何活动。谁能帮助我为什么?
progressBar1.Minimum = 0;
progressBar1.Maximum = (int)fileStream.Length + 1;
progressBar1.Value = 0;
using (fileStream)
{
fileStreamLength = (int)fileStream.Length + 1;
fileInBytes = new byte[fileStreamLength];
int currbyte = 0, i = 0;
var a = 0;
while (currbyte != -1)
{
currbyte = fileStream.ReadByte();
fileInBytes[i++] = (byte)currbyte;
progressBar1.Value=i;
}
}
答案 0 :(得分:2)
它正在递增,但你看不到它。它是由在UI线程中运行循环引起的。 查找BackGroundWorker或async / await模式。
答案 1 :(得分:0)
用户Method Invoker
更新用户界面...
试试这个...
在线程中完成所有工作,并在更新progressbar
时使用以下行...
对于Windows窗体
this.Invoke((MethodInvoker) delegate
{
progressBar1.value=i;
});
对于WPF
Dispatcher.BeginInvoke(new Action(delegate
{
progressBar1.value=i;
}));
答案 2 :(得分:0)
您最好的选择是Background Worker
从工具箱中拖放BackgroundWorker
。然后你必须实现2个功能:一个是后台工作,另一个是向UI报告。
using System.ComponentModel;
using System.Threading;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Start the BackgroundWorker.
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// begin reading your file here...
// set the progress bar value and report it to the main UI
int i = 0; // value between 0~100
backgroundWorker1.ReportProgress(i);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
}