是否可以知道Task Parallel.ForEach处理的当前文件
本文关键字:处理 文件 ForEach Parallel Task 是否 | 更新日期: 2023-09-27 17:57:57
请参阅:
private IEnumerable<string> _source;
public void doWork()
{
_tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
Task.Factory.StartNew(() =>
{
try
{
Parallel.ForEach(_source,
new ParallelOptions
{
MaxDegreeOfParallelism = _parallelThreads //limit number of parallel threads
},
file =>
{
if (token.IsCancellationRequested)
return;
//do work...
});
}
catch (Exception)
{ }
}, _tokenSource.Token).ContinueWith(
t =>
{
//finish...
}
, TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
);
}
这个方法接收了IEnumerable<string>
列表并同时处理我的文件,我想找到一种方法来了解处理的当前文件,我知道我可以使用file
变量和启动事件,但如果我的列表包含几个重复的文件,这将是一个问题,所以我的问题是,是否有方法知道当前列表索引正在处理中?
您说您可以知道当前字符串,但您可能有重复的问题,那么:
将CCD_ 3转换为CCD_。
private IEnumerable<Tuple<int,string>> WithIndecies(IEnumerable<string> _source)
{
int i =1;
return _source.Select(x => Tuple.Create(i++, x));
}
用法:
List<string> abc = new List<string>() { "a", "a", "b" };
var res = WithIndecies(abc);
结果:
(1,a)
(2,a)
(3,b)
编辑您的代码:
CancellationTokenSource _tokenSource;
private IEnumerable<string> _source;
int _parallelThreads = 10;
private Tuple<int,String> Currenct_Item;
public void doWork()
{
_tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
IEnumerable<Tuple<int,string>> _indexed_source = WithIndecies(_source);
Task.Factory.StartNew(() =>
{
try
{
Parallel.ForEach(_indexed_source,
new ParallelOptions
{
MaxDegreeOfParallelism = _parallelThreads //limit number of parallel threads
},
file =>
{
if (token.IsCancellationRequested)
return;
Currenct_Item = file; // Save CurrentFile and Access it from anywhere else to see current file being processed
// file.Item2 is the String so use it in the 'do work'
//do work...
});
}
catch (Exception)
{ }
}, _tokenSource.Token).ContinueWith(
t =>
{
//finish...
}
, TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
);
}
private IEnumerable<Tuple<int,string>> WithIndecies(IEnumerable<string> _source)
{
int i =1;
return _source.Select(x => Tuple.Create(i++, x));
}
如果你只想知道索引,有一个重载会发送一个表示索引的int64:
ForEach<TSource>(IEnumerable<TSource>, ParallelOptions, Action<TSource, ParallelLoopState, Int64>)
来自MSDN:
在IEnumerable上执行带有64位索引的foreach(Visual Basic中的For Each)操作,在该操作中,迭代可以并行运行,循环选项可以配置,循环状态可以监控和操作