gpt4 book ai didi

C# 进度条调用/委托(delegate)问题

转载 作者:行者123 更新时间:2023-11-30 12:15:02 24 4
gpt4 key购买 nike

我正在传输文件,想要一个进度条来显示每个文件的实际进度。这适用于 15 兆以下的文件,但大于 15 兆的文件似乎会导致我的应用程序卡住。如果我不为进度条调用此代码,这些较大的文件传输得很好。

我已经尝试了各种不同的方式来与代表一起处理这个问题,但没有成功。相反,它们适用于较小的文件,但不适用于较大的文件。

一些有效的例子...

pbFileProgress.Invoke((MethodInvoker)
delegate
{
pbFileProgress.Value = args.PercentDone;
});

此外,这组方法适用于较小的文件。

private delegate void SetProgressBarCallback(int percentDone);

public void UpdateProgressBar(object send, UploadProgressArgs args)
{
if (pbFileProgress.InvokeRequired)
{
var d = new SetProgressBarCallback(ProgressBarUpdate);
BeginInvoke(d, new object[] { args.PercentDone });
}
else
{
ProgressBarUpdate(args.PercentDone);
}
}

public void ProgressBarUpdate(int percentDone)
{
pbFileProgress.Value = percentDone;
}

但同样,如果我尝试更大的文件,一切都会卡住。

最佳答案

尽管缺乏上下文,但这里有一个有效的示例。 BeginInvoke 或 Invoke 方法最多只调用 100 次。

Task.Factory.StartNew(() =>
{
using (var source = File.OpenRead(@"D:\Temp\bbe.wav"))
using (var destination = File.Create(@"D:\Temp\Copy.wav"))
{
var blockUnit = source.Length / 100;

var total = 0L;
var lastValue = 0;

var buffer = new byte[4096];
int count;

while ((count = source.Read(buffer, 0, buffer.Length)) > 0)
{
destination.Write(buffer, 0, count);

total += count;

if (blockUnit > 0 && total / blockUnit > lastValue)
{
this.BeginInvoke(
new Action<int>(value => this.progressBar1.Value = value),
lastValue = (int)(total / blockUnit));
}
}

this.BeginInvoke(
new Action<int>(value => this.progressBar1.Value = value), 100);
}
});

关于C# 进度条调用/委托(delegate)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8406131/

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