我正面临着一种奇怪的虫子。我有大约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;
}
}
}
}当从单元测试中运行它时,请在ThreadAbortException中使用ComputePieceOfMatrix。
你知不知道?
编辑:
据评论,我试过这样做:
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();但情况完全一样。
发布于 2014-02-27 13:42:36
1.代码会导致异常。
try
{
for (int j = 0; j < 10000000000; j++) ;
}
catch (Exception e)
{
Console.Write(2);
throw;
}一个简单的OverflowException是10000000000 -是长和j计数器整数。
2.在子线程跑完之前,您的主要胎面就退出了。很可能是因为线程被运行时关闭,所以您得到了ThreadAbortException。
3.等待测试()
发布于 2014-02-27 13:33:47
将Test()的返回类型更改为Task,然后在程序结束之前等待该Task完成。
static void Main(string[] args)
{
Test().Wait();
}
public static async Task Test()
{
// ...
}发布于 2014-02-27 13:34:49
我会将您的测试从一个空类型更改为一个任务返回类型,在主要方法中,我将使用Test ()代替Test();
Task t = Test();
t.Wait();https://stackoverflow.com/questions/22069595
复制相似问题