gpt4 book ai didi

c# - 从 backgroundworker 获取错误值的进度

转载 作者:太空宇宙 更新时间:2023-11-03 19:27:31 29 4
gpt4 key购买 nike

我是 c# 的新手,我仍在努力学习它。

当我从 ftp 下载文件时,我已经为进度条制作了这段代码,它实际上工作得很好。但是进度值全错了。看起来它是某种字节值。但奇怪的是,当我将值打印到屏幕上时,它会打印出正确的值。

private void frm_movie_db_Load(object sender, EventArgs e)
{
if (!File.Exists("movies.list.gz"))
{
bg_worker.RunWorkerAsync();
}
}

private void bg_worker_DoWork(object sender, DoWorkEventArgs e)
{
string strDownloadFrom = "ftp://ftp.sunet.se/pub/tv+movies/imdb/movies.list.gz";
string strDownloadTo = "movies.list.gz";

try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(strDownloadFrom);

request.Method = WebRequestMethods.Ftp.GetFileSize;
request.Credentials = new NetworkCredential("anonymous", "");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;

Int64 intFileSize = request.GetResponse().ContentLength;
Int64 intRunningByteTotal = 0;

request = (FtpWebRequest)FtpWebRequest.Create(strDownloadFrom);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential("anonymous", "");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream reader = response.GetResponseStream();

Stream writer = new FileStream(strDownloadTo, FileMode.Create, FileAccess.Write, FileShare.None);
byte[] byteBuffer = new byte[1024];

int intByteSize = 0;
int intProgressPct = 0;

while ((intByteSize = reader.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
if (intByteSize == 0)
{
intProgressPct = 100;
bg_worker.ReportProgress(intProgressPct);
}
else
{
writer.Write(byteBuffer, 0, intByteSize);

if (intByteSize + intRunningByteTotal <= intFileSize)
{
intRunningByteTotal += intByteSize;
double dIndex = intRunningByteTotal;
double dTotal = byteBuffer.Length;
double dProgressPct = (double)(dIndex / dTotal);
intProgressPct = (int)dProgressPct;
bg_worker.ReportProgress(intProgressPct);
}
}
}

//reader.Close();
//mem_stream.Close();
//response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

private void bg_worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//pb_download_files.Value = e.ProgressPercentage;
lbl_progress_pct.Text = e.ProgressPercentage.ToString() + "%";
}

private void bg_worker_RunWorkerComplete(object sender, RunWorkerCompletedEventArgs e)
{
pnlProgress.Visible = false;
}

我希望有人能帮我解决这个问题,因为到目前为止我已经做了一切来自己解决这个问题。

最好的问候杰斯珀

最佳答案

您在百分比进度计算上完全错误:perc 必须是100 x 当前/总计,所以您使用了错误的值。

试试这个:

double dProgressPct = 100.0 * intRunningByteTotal / intFileSize;
bg_worker.ReportProgress((int)ProgressPct);

阅读Microsoft documentation :

public void ReportProgress(int percentProgress)

其中 percentageProgress 是后台操作完成的百分比,从 0 到 100。

关于c# - 从 backgroundworker 获取错误值的进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7513741/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com