这是我获取IEnumerable<string> source
和搜索此路径中所有文件的函数:
public void search()
{
Task.Factory.StartNew(() =>
{
try
{
Parallel.ForEach(_source,
new ParallelOptions
{
MaxDegreeOfParallelism = 5 //limit number of parallel threads here
},
file =>
{
FileChecker fileChecker = new FileChecker();
string result = fileChecker.check(file);
if (result != null)
OnFileAddEvent(result);
});
}
catch (Exception)
{ }
}).ContinueWith
(t =>
{
OnFinishSearchEvent();
}
, TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
);
}
public void search2()
{
Task.Factory.StartNew(() =>
{
var filtered = _source.AsParallel()
.WithDegreeOfParallelism(5)
.Where(file =>
{
try
{
FileChecker fileChecker = new FileChecker();
string result = fileChecker.check(file);
if (result != null)
OnFileAddEvent(result);
return true;
}
catch (Exception)
{
return false;
}
});
return filtered.ToList();
}).ContinueWith
(t =>
{
OnFinishSearchEvent();
}
, TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
);
}