我想在按下按钮时显示每个文件的路径。 我现在拥有的是一个迭代文件夹并显示路径的函数,但仅在函数完成时:
public void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
try
{
var fileEntries = Directory.GetFiles(targetDirectory);
foreach (var fileName in fileEntries)
{
ProcessFile(fileName);
}
}
catch (Exception e){}
// Recurse into subdirectories of this directory.
try
{
var subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
catch (Exception e){}
}
public void ProcessFile(string path)
{
myListBox.Items.Add(path);
}
这意味着我必须等待才能做其他事情。 如何在函数运行时立即显示文件的路径,所以我不必在函数完成之前等待,在列表框中显示之前获取所有路径?
答案 0 :(得分:1)
我不记得我在哪里遇到过这段代码,但是如果你将ProcessFile方法修改为类似的东西,它会在每个项目添加到你的列表后更新你的UI。
public void ProcessFile(string path)
{
myListBox.Items.Add(path);
myListBox.ScrollIntoView(myListBox.Items[myListBox.Items.Count-1]);
Dispatcher.Invoke(new Action(delegate { }), DispatcherPriority.Background);
}
我想我记得在某个地方读过这个“黑客”不会被推荐,因为可能会出现许多其他问题,但我不记得它是什么或我在哪里阅读它。然而,它完成了这项工作。
也许其他人可以告诉我们这些问题是什么......
答案 1 :(得分:0)
这使您的方法在另一个线程上运行:
public void StartProcessThread(string targetDirectory)
{
Thread T = new Thread(new ParameterizedThreadStart(ProcessDirectory));
T.Start(targetDirectory);
}
public void ProcessDirectory(object objTargetDirectory)
{
string targetDirectory = (string)objTargetDirectory;
// Process the list of files found in the directory.
try
{
var fileEntries = Directory.GetFiles(targetDirectory);
foreach (var fileName in fileEntries)
{
ProcessFile(fileName);
}
}
catch (Exception e){}
// Recurse into subdirectories of this directory.
try
{
var subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
catch (Exception e){}
}
public void ProcessFile(string path)
{
Dispatcher.Invoke(new Action(() => {
myListBox.Items.Add(path);
}));
}