【发布时间】:2014-03-30 22:42:22
【问题描述】:
我正面临一个奇怪的错误。 我有大约 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();
但是完全一样。
【问题讨论】:
-
等等,什么?
async void?我想你的意思是async Task。 -
Resharper 告诉我,如果我不使用它,返回一个任务是没有用的。我会尝试使用它。
-
我猜你的主线程在
Test完成之前就退出了,而现有线程在应用程序退出之前就被中止了。 -
我已经编辑了我的问题。这不起作用...谢谢!
标签: c# multithreading exception task async-await