我有一个包含2个列表框的程序,该程序被低音搜索到文件,然后与StopWatch
使用AsyncAwait
和TPL的区别进行比较...第一个列表框使用以下功能AsyncAwait
(我不知道这是否是更好的方法)可以,但是可以,请参见下面的代码)
private async void button1_Click(object sender, EventArgs e)
{
Stopwatch stopWatch = new Stopwatch();
foreach (string d in Directory.GetDirectories(@"C:\Visual Studio Projectes\Hash\AsyncAwait\Carpetes"))
{
foreach (string s in Directory.GetFiles(d))
{
stopWatch.Start();
listBox1.Items.Add(s);
await Task.Delay(1);
btIniciar1.Enabled = false;
}
}
btIniciar1.Enabled = true;
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
textBox1.Text = ts.ToString("mm\\:ss\\.ff") + (" minuts");
}
然后在我的第二个列表框中,我陷入了困境,我不知道如何实现Parallel.ForEach
行为async
,有什么更好的方法呢?在这种情况下,我找不到使用TPL的方法来完成与我的第一个列表框相同的操作,请您能帮我吗?
最后,我已经解决了这个问题:
DirectoryInfo nodeDir = new DirectoryInfo(@"c:\files");
Parallel.ForEach(nodeDir.GetDirectories(), async dir =>
{
foreach (string s in Directory.GetFiles(dir.FullName))
{
Invoke(new MethodInvoker(delegate { lbxParallel.Items.Add(s); }));
contador++;
await Task.Delay(1);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句