CSharp · Console
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var partitioner = Partitioner.Create(YieldedNumbers());
Parallel.ForEach(
partitioner.AsParallel(),
(n) => {
var threadId = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine($"{threadId} run at {DateTime.Now}");
Thread.Sleep(500);
});
Console.WriteLine("Done!");
Console.ReadLine();
}
public static IEnumerable<int> YieldedNumbers()
{
Random rnd = new Random();
int lastKnownThread = Thread.CurrentThread.ManagedThreadId;
int detectedSwitches = 0;
for (int i = 0; i < 100; i++)
{
int currentThread = Thread.CurrentThread.ManagedThreadId;
if (lastKnownThread != currentThread)
{
detectedSwitches++;
var st = $"{detectedSwitches}: Last known thread ({lastKnownThread}) is not the same as the current thread ({currentThread}).";
Console.WriteLine(st);
lastKnownThread = currentThread;
}
yield return rnd.Next(10,150);
}
}
}