【发布时间】:2011-03-04 15:10:09
【问题描述】:
我试图围绕整个并行编程概念,主要关注任务,所以我一直在尝试这种情况,例如,多达 9 个并行任务会在随机的一段时间内执行它们的工作:
/// <remarks>
/// A big thank you to the awesome community of StackOverflow for
/// their advice and guidance with this sample project
/// http://stackoverflow.com/questions/5195486/
/// </remarks>
RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
byte[] buffer = new byte[4];
random.GetBytes(buffer);
// Creates a random number of tasks (not less than 2 -- up to 9)
int iteration = new Random(BitConverter.ToInt32(buffer, 0)).Next(2,9);
Console.WriteLine("Creating " + iteration + " Parallel Tasks . . .");
Console.Write(Environment.NewLine);
Dictionary<int, string> items = new Dictionary<int, string>();
for (int i = 1; i < iteration + 1; i++) // cosmetic +1 to avoid "Task N° 0"
{
items.Add(i, "Task # " + i);
}
List<Task> tasks = new List<Task>();
// I guess we should use a Parallel.Foreach() here
foreach (var item in items)
{
// Creates a random interval to pause the thread at (up to 9 secs)
random.GetBytes(buffer);
int interval = new Random(BitConverter.ToInt32(buffer, 0)).Next(1000, 9000);
var temp = item;
var task = Task.Factory.StartNew(state =>
{
Console.WriteLine(String.Format(temp.Value + " will be completed in {0} miliseconds . . .", interval));
Thread.Sleep(interval);
return "The quick brown fox jumps over the lazy dog.";
}, temp.Value).ContinueWith(t => Console.WriteLine(String.Format("{0} returned: {1}", t.AsyncState, t.Result)));
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
但不幸的是,它们是按顺序而不是并行处理的。
如果你们能在这里帮助我,我会非常高兴——也许我应该使用 Parallel.ForEach 而不是常规的?
再次感谢任何建议。
编辑 两次更新代码示例以反映评论者的贡献。
【问题讨论】:
标签: c# parallel-processing task task-parallel-library