I find naming threads to be very useful when debugging.
I can see no way to name a thread using arguments to Task.Factory.StartNew()
So is it acceptable to name the thread explicitly in the task? eg:
private void MyFunc()
{
Task.Factory.StartNew(() =>
{
Thread.CurrentThread.Name = "Foobulizer";
Foobulize();
});
}
However, I appreciate that threads may be reused for different tasks, so would I need to explicitly reset the thread name at the end of the task? This feels pretty hacky so I'm thinking this is probably a bad idea, or there's a proper way to do it?
The default
TaskScheduler
uses the .NETThreadPool
to schedule the tasks. So you will get a thread that already exists or one that will be reused (both potentially, but likely).Note that you can only name a thread once. The second attempt to call
Thread.CurrentThread.Name
will raise anInvalidOperationException
. This is particularly bad when it is a thread pool thread.In general you should not change attributes of a thread that you did not (explicitly) create or own (the name being one, the priority being the other prominent candidates).
Sure you can, just remove the Name again when you're done. set the thread Name again to "Idle" ore string.Empty after Foobulize();
You can not do this since multiple Tasks can share single or multiple threads depends on ThreadPool state in a given moment of time. Basically Task is not a Thread this is just a high level abstraction for the asynchronous operation. You can use Task.Id property but keep in mind that
Id
is readonly and ofint
type so you can't assign custom user-friendly name.Take a look at the built in Visual Studio 2010 Parallel Debugging features, perhaps you'll find an other approach: Walkthrough: Debugging a Parallel Application
Parallel Tasks Window: