我有一个应用程序,我正在其中分块上传文件。我的前端是WPF,我有一个进度条来显示文件上传进度(上传是由单独的线程完成的,进度条采用单独的形式,在上传开始时由子线程调用)。
我找到了文件中的块总数来设置进度条的最大属性。
现在,对于上传的每个块,我将进度条的值增加 1。
但令我惊讶的是,进度条开始增加但从未完成(几个块后它停止显示进度)。
以下是负责上传文件的线程的代码:
System.Threading.Thread thread = new Thread(
new ThreadStart(
delegate()
{
// show progress bar - Progress is the name of window containing progress bar
Progress win = new Progress();
win.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
win.Show();
// find number of blocks
long BlockSize = 4096;
FileInfo fileInf = new FileInfo(filename);
long FileSize = fileInf.Length;
long NumBlocks = FileSize / BlockSize;
//set the min and max for progress bar
win.Dispatcher.Invoke(
new Action(
delegate()
{
win.progressBar1.Minimum = 0;
win.progressBar1.Maximum = NumBlocks;
}
), System.Windows.Threading.DispatcherPriority.Render);
//upload file
while (true)
{
// code to upload the file
win.Dispatcher.Invoke(
new Action(
delegate()
{
win.progressBar1.Value += 1;
}
), System.Windows.Threading.DispatcherPriority.Render);
}
}
有人可以帮我分析一下为什么会发生这种情况吗?
Thanks.
问题是这样的:
上传是由单独的线程完成的,并且
进度条是单独的形式
当子线程调用时
上传开始
如果这意味着您的子线程创建了表单,那么这就是问题所在。您的子线程可能正在更新进度条值,但这只会使显示无效,并且不一定会刷新显示。当控件的显示无效时,它只是记录下一次有机会时必须重绘其显示。 刷新是指控件实际渲染到屏幕上的时间。
更好的方法是在main线程中创建进度条表单。
然后,您的工作线程可以更新状态,并且您的主线程将刷新显示。
要记住的一件事:如果您要更新在不同线程中创建的控件,则必须通过控件的调度程序来执行此操作。
var dispatcher = progressBar.Dispatcher;
dispatcher.BeginInvoke(new Action( () => { progressBar.Value = currentProgress }));
Edit after seeing the code
您需要做的就是移动进度变量的创建,以便在创建工作线程之前由主线程实例化它。
Progress win = new Progress();
win.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
win.Show();
System.Threading.Thread thread = new Thread(
new ThreadStart(
delegate()
{
// ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)