我在我的函数中打开n个并发线程:
List<string> _files = new List<string>();
public void Start()
{
CancellationTokenSource _tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
Task.Factory.StartNew(() =>
{
try
{
Parallel.ForEach(_files,
new ParallelOptions
{
MaxDegreeOfParallelism = 5 //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
);
}
有一种方法可以知道这个函数还在处理1个文件吗?我现在正在谈论ContinueWith
,在我list
完成所有情况之后就是这种情况。
答案 0 :(得分:0)
不确定我是否完全理解您的问题,但您可以通过某种方法使用某些标准通知:
public void Start()
{
CancellationTokenSource _tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
Task.Factory.StartNew(() =>
{
try
{
Parallel.ForEach(_files,
new ParallelOptions
{
MaxDegreeOfParallelism = 5 //limit number of parallel threads
},
file =>
{
if (token.IsCancellationRequested)
return;
//do work...
OnDone(file);
});
}
catch (Exception)
{ }
}, _tokenSource.Token).ContinueWith(
t =>
{
//finish...
}
, TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
);
}
public void OnDone(string fileName)
{
// Update the UI, assuming you're using WPF
someUIComponent.Dispatcher.BeginInvoke(...)
}
如果更新某些共享状态,则可能需要额外的锁,但只更新UI(例如,数据网格中的行或列表中的元素)应该没问题,因为调度程序调用会强制执行同步。 p>