【发布时间】:2015-04-09 01:03:57
【问题描述】:
我正在使用 C# 和 WPF 开发应用程序。我正在使用 3 个嵌套的 Parallel.For 循环,如下所示。当我Cancel() 令牌时,循环开始抛出ImportAbortedException 但是,我无法捕捉ImportAbortedException。我咳的是AggregateException
我想要的是,停止所有 Parallel.Fors 并抓住 ImportAbortedException 并做一些其他的事情。
这里是代码。
private int _loopCount1 = 100;
private int _loopCount2 = 200;
private int _loopCount3 = 10000;
private CancellationToken _cToken;
private CancellationTokenSource _cSource;
private void Init()
{
_cSource = new CancellationTokenSource();
_cToken = new CancellationToken();
_cToken = _cSource.Token;
try
{
DoTheWork();
}
catch (ImportAbortedException)
{
///
}
catch (Exception)
{
}
}
private void StopAllLoops()
{
_cSource.Cancel();
}
private void DoTheWork()
{
Parallel.For(0, _loopCount1, i =>
{
if (CheckIfCanceled())
throw new ImportAbortedException("process aborted!");
// do a few calculations here.
Parallel.For(0, _loopCount2, j =>
{
if (CheckIfCanceled())
throw new ImportAbortedException("process aborted!");
// do a few calculations here.
Parallel.For(0, _loopCount3, k =>
{
if (CheckIfCanceled())
throw new ImportAbortedException("process aborted!");
// do some other process here.
});
});
});
}
private bool CheckIfCanceled()
{
return _cToken.IsCancellationRequested;
}
【问题讨论】:
-
取消任务是很正常的操作。为什么首先抛出异常?
-
因为我想了解是计算进度抛出异常还是导入取消。
标签: c# wpf parallel.for