gpt4 book ai didi

C# progressBar 在完成一半进度之前不会更新

转载 作者:行者123 更新时间:2023-11-30 22:04:05 24 4
gpt4 key购买 nike

我正在使用 dispatcherTimer 来更新 progressBar 的值:

DispatcherTimer tim = new DispatcherTimer();
tim.Interval = TimeSpan.FromMilliseconds(100);
tim.Tick += delegate
{
if (valuee < max)
{
prog.Value = valuee;
}
else
{
tim.Stop();
}
};

然后像这样设置进度条的最大值:

using (FileStream fs = File.Open(Filename, FileMode.Open))
{
if (fs.Length > 10485760 && fs.Length <= 209715200)
prog.Maximum = fs.Length / 1024;
else if (fs.Length <= 10485760)
prog.Maximum = fs.Length / 16;
else if(fs.Length > 209715200)
prog.Maximum = fs.Length / 1048576;
}

然后在 for 循环的每次迭代后增加值:

var Input = File.OpenRead(path);
int Size = MainWindow.prog.Maximum;
for (long i = 0; i < Input.Length; i += Size)
{
MainWindow.valuee++;
PasswordEnter.valuee++;
byte[] chunkData = new byte[chunkSize];
int bytesRead = 0;
while ((bytesRead = fsInput.Read(chunkData, 0, chunkSize)) > 0)
{
if (bytesRead != chunkSize)
{
for (int x = bytesRead - 1; x < chunkSize; x++)
{
chunkData[x] = 0;
}
}
cryptoStream.Write(chunkData, 0, bytesRead);
}
}

编辑:这就是我调用 AESCryptography 类的方式:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, l) => lo.Encrypt(Filename, password.Password, "main");
worker.RunWorkerAsync();

但由于某种原因,progressBar 直到超过一半的迭代结束后才会更新!怎么了?

最佳答案

A DispatcherTimer队列在 Dispatcher 线程上工作,这是 WPF UI 线程。

这是 MSDN 关于计时器执行的说法:

The DispatcherTimer is reevaluated at the top of every Dispatcher loop. Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.

您正在经历进度计时器的延迟,因为您很可能正在运行一个长时间阻塞操作,该操作拒绝处理不同请求的消息循环。

你有两个选择:

  1. 将长时间运行的操作移至后台线程。我更喜欢这种方法。

  2. 尝试使用 DispatcherTimer overload这需要 DispatcherPriority并指定更高的优先级。这种方法仍然不能保证您会体验到性能变化,但它可能会有所帮助。

关于C# progressBar 在完成一半进度之前不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25490997/

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