[英]Progress Bar in WPF - stuck in 50%
所以我在它的 GUI 上有一个带有 BackgroundWorker 和 ProgressBar 的类,就像这样
public class mCrypt
{
public byte[] DataBlock;
public byte[] IVBlock;
public static Bitmap FingerprintImg;
public byte[] TempX;
public byte[] TempAngles;
public byte[] TempY;
public byte[] TempKey;
public byte[] X;
public byte[] Y;
public byte[] Angles;
public byte[] Key;
public int NoM;
public mCrypt(BackgroundWorker bw, string imgLoc, string fileLoc, byte[] ivBlock)
{
if (!bw.CancellationPending)
{
bw.ReportProgress(0);
LoadImg(imgLoc);
bw.ReportProgress(7);
DetectMinutiae(FingerprintImg);
bw.ReportProgress(25);
ConvertValues();
bw.ReportProgress(30);
LoadFile(fileLoc);
// This LoadFile method contains DataBlock = File.ReadAllBytes(fileloc);
bw.ReportProgress(35);
HandleLength(ivBlock);
bw.ReportProgress(40);
ManageInitKey();
bw.ReportProgress(45);
GenerateKey();
bw.ReportProgress(50);
}
}
public byte[] EncryptFile(BackgroundWorker bgw)
{
if(!bw.CancellationPending)
{
for(int i = 0, i < (DataBlock.Length / 16), i++)
{
//Doing cryptographical process here
...
//ProgressBar updates
if((i / (DataBlock.Length / 16)) + 50 != 100)
bgw.ReportProgress((i / (DataBlock.Length / 16)) + 50);
else
bgw.ReportProgress(100);
}
}
}
}
当我尝试运行该应用程序时,ProgressBar 仅在构造函数运行时更新。 将 ProgressBar 保持在 50% 状态,直到进程完成。 我不明白为什么它不起作用。 任何的想法? 提前致谢
您没有正确使用您的BackgroundWorker
,并且您锁定了 UI 线程。
将调用移动到LoadImg()
, LoadFile();
和ReportProgress()
进入DoWork
事件。 此外,如果这些方法完全接触 UI,您可能需要修改这些方法正在执行的操作。
我还建议阅读此内容: C# 中的线程:BackgroundWorker
不要直接从background worker
进程接触UI thread
。 使用Invoke
或BeginInvoke
修改UI
内部工作进程线程:
bw.DoWork += (sender, args) =>
{
Dispatcher.BeginInvoke(DispatcherPriority.Loaded,new Action(()=>
{
//code that changes progress-bar
}
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.