foreach 循环中的委托和调度程序无法访问当前项目
我正在尝试在 WPF 中实现进度条。我正在循环访问文件路径列表(List)并对文件执行一些操作。我想跟踪该过程的进度,但它无法正常工作。在这种情况下,每次调用 tagAndMoveFiles() 方法时,都会使用 foreach 列表中的相同项目来调用它,但调用的次数是正确的。我不太擅长与代表打交道(显然)...我已经包含了所有相关代码。感谢您的帮助。 (uploadProgress为进度条)
uploadProgress.Maximum = impJob.SourceFilePaths.Count;
DispatcherTimer timer = new DispatcherTimer();
int progress = 0;
foreach (string sourcefilepath in impJob.SourceFilePaths)
{
Thread t = new Thread(new ThreadStart(
delegate()
{
uploadProgress.Dispatcher.BeginInvoke(DispatcherPriority.Loaded,
new Action(
delegate
{
tagAndMoveFiles(sourcefilepath, targetFolder, impJob, sourceFileProcessed);
uploadProgress.Value = ++progress;
Thread.Sleep(100);
}
));
}
));
t.Start();
}
I'm trying to implement a progress bar in WPF. I am looping through a list of file paths (List) and performing some operations on the files. I want to track the progress of the process but it is not working correctly. In this case each time the method tagAndMoveFiles() is called it is called with the same item from the foreach list but it is called the proper number of times. I'm not very good with delegates (obviously)...I've included all relevant code. Thanks for your help. (uploadProgress is the progress bar)
uploadProgress.Maximum = impJob.SourceFilePaths.Count;
DispatcherTimer timer = new DispatcherTimer();
int progress = 0;
foreach (string sourcefilepath in impJob.SourceFilePaths)
{
Thread t = new Thread(new ThreadStart(
delegate()
{
uploadProgress.Dispatcher.BeginInvoke(DispatcherPriority.Loaded,
new Action(
delegate
{
tagAndMoveFiles(sourcefilepath, targetFolder, impJob, sourceFileProcessed);
uploadProgress.Value = ++progress;
Thread.Sleep(100);
}
));
}
));
t.Start();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
委托每次循环都会捕获相同的实例。所以你需要在循环内添加一个局部变量,如下所示......
The delegate is capturing the same instance each time around the loop. So you need to add a local variable inside the loop like this...
您遇到了这个问题: 访问修改后的闭包 (2)
简而言之:您需要在
foreach
循环内有一个局部变量来捕获sourcefilepath
并将其传递给委托。You ran into this problem: Access to Modified Closure (2)
Short: you need to have a local variable inside your
foreach
loop to capture thesourcefilepath
and pass that to the delegate.