本文整理汇总了C#中System.Threading.Tasks.Task.ForEach方法的典型用法代码示例。如果您正苦于以下问题:C# Task.ForEach方法的具体用法?C# Task.ForEach怎么用?C# Task.ForEach使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Tasks.Task
的用法示例。
在下文中一共展示了Task.ForEach方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TaskFromPromiseWithResultIndexWorksWhenPromiseCompletes
public void TaskFromPromiseWithResultIndexWorksWhenPromiseCompletes() {
var promise = CreatePromise();
var tasks = new Task<int>[] {
Task.FromPromise<int>(promise, 0),
Task.FromPromise<int>(promise, 1),
Task.FromPromise<int>(promise, 2),
Task.FromPromise<int>(promise, -3),
Task.FromPromise<int>(promise, -2),
Task.FromPromise<int>(promise, -1),
};
var continuationsRun = new bool[6];
Assert.IsTrue(tasks.Every(t => t.Status == TaskStatus.Running), "Tasks should be running after being created");
tasks.ForEach((x, i, _) => x.ContinueWith(t => {
Assert.IsTrue(t == x, "ContinueWith parameter should be correct");
continuationsRun[i] = true;
}));
Window.SetTimeout(() => {
Assert.IsFalse(continuationsRun.Some(x => x), "Continuations should not be run too early.");
Assert.IsTrue(tasks.Every(t => t.Status == TaskStatus.Running), "Tasks should be running before promise is completed.");
promise.Resolve(10, 42, 38);
}, 100);
Window.SetTimeout(() => {
Assert.IsTrue(tasks.Every(t => t.Status == TaskStatus.RanToCompletion), "Task should be completed after promise");
Assert.IsTrue(continuationsRun.Every(x => x), "Continuations should have been run after promise was completed.");
Assert.AreEqual(tasks[0].Result, 10, "Task 0 result should be correct");
Assert.AreEqual(tasks[1].Result, 42, "Task 1 result should be correct");
Assert.AreEqual(tasks[2].Result, 38, "Task 2 result should be correct");
Assert.AreEqual(tasks[3].Result, 10, "Task 3 result should be correct");
Assert.AreEqual(tasks[4].Result, 42, "Task 4 result should be correct");
Assert.AreEqual(tasks[5].Result, 38, "Task 5 result should be correct");
QUnit.Start();
}, 200);
}
示例2: SpinParallel
/// <summary>
/// Runs given function in parallel on multiple tasks.
/// Number of tasks spawned matches number of logical processors.
/// </summary>
/// <param name="millisecondsToRun"></param>
/// <param name="funcToTest"></param>
/// <returns></returns>
public static long SpinParallel(long millisecondsToRun, Action funcToTest)
{
Task<long>[] tasks = new Task<long>[Environment.ProcessorCount];
for(int i = 0; i < Environment.ProcessorCount; i++)
{
tasks[i] = new Task<long>(() => Spin(millisecondsToRun, funcToTest));
}
DateTime start = DateTime.UtcNow;
tasks.ForEach(task => task.Start());
// ReSharper disable once CoVariantArrayConversion
Task.WaitAll(tasks);
long ranMillisec = (long)(DateTime.UtcNow - start).TotalMilliseconds;
Debug.WriteLine("Parallel call counting run time mismatch is {0:#,#} milliseconds.", ranMillisec - millisecondsToRun);
long[] runCounts = tasks.Select(thread => thread.Result).ToArray();
long total = runCounts.Sum();
return total;
}