我遇到了一个奇怪的错误。
我有大约100个长时间运行的任务,我想同时运行其中的10个。
我在这里找到了与我的需求非常相似的内容:http://msdn.microsoft.com/en-us/library/hh873173%28v=vs.110%29.aspx 在节流部分。
这里是简化后的C#代码:
我在这里找到了与我的需求非常相似的内容: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();
但这完全相同。
async void
?我想你是指async Task
。 - Steven LiekensTest
完成之前就退出了,应用程序退出之前现有的线程被中止。 - Lee