WPF 中的进度条 - 卡在 50%
本文关键字:卡在 WPF | 更新日期: 2023-09-27 17:56:57
所以我有一个类,它的GUI上有一个BackgroundWorker 和一个进度条,像这样
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);
}
}
}
}
当我尝试运行该应用程序时,进度条仅在构造函数运行时更新。将进度条保持在 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
}
));
}