List.AsParallel() - how can I name my threads?
I use
List.AsParallel().WithDegreeOfParallelism(3).ForAll(x => Worker(x));
to apply Worker on each element of the list.
How can I name the threads on which Worker runs, so that when each Worker(x) thread is termi开发者_开发问答nated the VS debugger tells me: Thread <<for elem abcde>> terminated
, so that I can differentiate between threads?
I need this because the program just stops executing elements in the list after some time, and the threads just terminate.
I'm using Thread.CurrentThread.ManagedThreadId
to see which thread is being reused.
The idea is shown in the test below:
[Test]
public void ThreadNamesTest()
{
var rnd = new Random();
var range = Enumerable.Range(0, 50);
var rangeBack = new Dictionary<int, int>();
var rangeBackLocker = new object();
range.AsParallel().AsOrdered()
.WithDegreeOfParallelism(4).ForAll(x =>
{
lock (rangeBackLocker)
{
rangeBack.Add(x, Thread.CurrentThread.ManagedThreadId);
}
Thread.Sleep(100 * rnd.Next(10));
});
Assert.AreEqual(rangeBack.GroupBy(x=>x.Value).Count(), 4);
}
You could probably set the thread name in your Worker
method:
Thread.CurrentThread.Name = "PLinq Thread: " + x
However threads will be reused (and not necessarily terminated when your work is done, if they're put back into a pool), so you won't see them being terminated for each item in your collection - you'll just probably see the names of the last items from each thread, in the termination messages.
Edit: Gilad points out in comments, an exception will be thrown if you try to set the name of a thread that already has a name. I guess this makes what you're trying to do completely impossible, given threads can be reused.
PLinq doesn't create a new thread for each element that it processes, it can process multiple elements on a single thread, so I don't think naming the threads is really what you need here.
I'd suggest that at the start of Worker, you write out to the debug console the current element, and the ID of the current thread. Then when a thread is terminated, you'll be able to check your debug output to see which was the last element to be started on that thread.
精彩评论