110,524
社区成员
发帖
与我相关
我的任务
分享
XX(Action action){
}
调用类似:
XX(()=>{
//TODO:
});
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(h =>
{
处理(new DirectoryInfo("c:\\mmm"));
this.listBox1.Items.Add("结束");
});
}
private bool 处理(DirectoryInfo dir)
{
this.listBox1.BeginInvoke((Action)delegate
{
this.listBox1.Items.Add(dir.FullName);
});
(from f in dir.EnumerateFiles("*.txt").AsParallel()
select 处理(f)).Count();
(from d in dir.EnumerateDirectories().AsParallel()
select 处理(d)).Count();
return true;
}
private bool 处理(FileInfo file)
{
if (File.ReadAllText(file.FullName).Contains("a"))
{
this.listBox1.BeginInvoke((Action)delegate
{
this.listBox1.Items.Add("找到一个文件======>" + file.FullName);
});
return true;
}
else
return false;
}
}
}
你可以看到,在button1点击之后,窗体其它交互操作可以继续,并不会“卡住”。文件遍历查找工作是在子线程中进行的。