我有这两种方法
private List<DirectoryInfo> GetDirectories(string basePath)
{
IEnumerable<string> str = MyGetDirectories(basePath);
List<DirectoryInfo> l = new List<DirectoryInfo>();
l.Add(new DirectoryInfo(basePath));
IEnumerable<DirectoryInfo> dirs = str.Select(a => new DirectoryInfo(a));
l.AddRange(dirs);
return l;
}
并且
static int countDirectories = 0;
private IEnumerable<string> MyGetDirectories(string basePath)
{
try
{
string[] dirs = Directory.GetDirectories(basePath);
if (dirs.Length > 0)
return dirs.Union(dirs);
countDirectories = countDirectories + dirs.Length;
_FileInformationWorker.ReportProgress(countDirectories,dirs);
return dirs.Union(dirs.SelectMany(dir => MyGetDirectories(dir)));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
在背景工作者看来这个
private void _FileInformationWorker_DoWork(object sender, DoWorkEventArgs e)
{
MySubDirectories = GetDirectories(BasePath).ToArray();
}
而是等待方法MyGetDirectories完成我想在每次变量dirs时在dowork事件中更新变量MySubDirectories。更改。在这种情况下,第一次dirs长度为36,所以我返回,我看到MySubDirectories包含36个项目。现在的问题是MyGetdirectories方法中的递归不会继续。我希望它继续,所以下次dirs长度大于0,例如下次它将是3然后更新MySubDirectories所以现在MySubDirectories将包含dirs中的新3项。
我不想停止递归我只想实时更新MySubDirectories。
到目前为止,我尝试过的是MyGetdirectories方法,我也报告了dirs变量:
_FileInformationWorker.ReportProgress(countDirectories, dirs);
然后在progresschanged事件中做了:
List<string[]> testing = new List<string[]>();
private void _FileInformationWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label2.Text = e.ProgressPercentage.ToString();
string[] test = (string[])e.UserState;
if (test.Length > 0)
testing.Add(test);
}
但现在我结束了一个string []数组列表。并且测试是字符串[] 有没有办法将字符串[]转换/转换为DirectoryInfo []?
答案 0 :(得分:0)
来自https://www.microsoft.com/en-us/download/details.aspx?id=14782
// Hand-off through a BufferBlock<T>
private static BufferBlock<int> m_buffer = new BufferBlock<int>();
// Producer
private static void Producer()
{
while(true)
{
int item = Produce();
m_buffer.Post(item);
}
}
// Consumer
private static async Task Consumer()
{
while(true)
{
int item = await m_buffer.ReceiveAsync();
Process(item);
}
}
// Main
public static void Main()
{
var p = Task.Factory.StartNew(Producer);
var c = Consumer();
Task.WaitAll(p,c);
}
答案 1 :(得分:-1)
这应该有效:
test.Select(p =&gt; new DirectoryInfo(p))。ToArray();