我遇到了一个奇怪的错误。 我有大约 100 个长时间运行的任务,我想同时运行其中的 10 个。
我在这里找到了与我的需求非常相似的东西:http://msdn.microsoft.com/en-us/library/hh873173%28v=vs.110%29.aspx在节流部分。
这里是简化后的C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
Test();
}
public static async void Test()
{
var range = Enumerable.Range(1, 100).ToList();
const int CONCURRENCY_LEVEL = 10;
int nextIndex = 0;
var matrixTasks = new List<Task>();
while (nextIndex < CONCURRENCY_LEVEL && nextIndex < range.Count())
{
int index = nextIndex;
matrixTasks.Add(Task.Factory.StartNew(() => ComputePieceOfMatrix()));
nextIndex++;
}
while (matrixTasks.Count > 0)
{
try
{
var imageTask = await Task.WhenAny(matrixTasks);
matrixTasks.Remove(imageTask);
}
catch (Exception e)
{
Console.Write(1);
throw;
}
if (nextIndex < range.Count())
{
int index = nextIndex;
matrixTasks.Add(Task.Factory.StartNew(() => ComputePieceOfMatrix()));
nextIndex++;
}
}
await Task.WhenAll(matrixTasks);
}
private static void ComputePieceOfMatrix()
{
try
{
for (int j = 0; j < 10000000000; j++) ;
}
catch (Exception e)
{
Console.Write(2);
throw;
}
}
}
}
当从单元测试运行它时,在 ComputePieceOfMatrix 中有一个 ThreadAbortException。
你有什么想法吗?
编辑:
根据评论,我试过这个:
static void Main(string[] args)
{
Run();
}
private static async void Run()
{
await Test();
}
public static async Task Test()
{
var range = Enumerable.Range(1, 100).ToList();
但是完全一样。
最佳答案
1.你的代码导致异常
try
{
for (int j = 0; j < 10000000000; j++) ;
}
catch (Exception e)
{
Console.Write(2);
throw;
}
只是一个简单的 OverflowException,因为 10000000000 - 是 long 且 j 是 counter int。
2.您的主线程在子线程运行完成之前退出。您很可能会收到 ThreadAbortException,因为线程已被运行时关闭
3.await Test() - 正确地调用 Test(),并在没有 await 的情况下等待 Task.WhenAny
关于c# - 带等待的 ThreadAbortException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22069595/