Is there a way to specify a Thread's name when using the Task.StartNew
method
var task = Task.Factory.StartNew(MyAction, TaskCreationOption.LongRunning, ??ThreadName??);
Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!
A task can have multiple processes happening at the same time. Threads can only have one task running at a time. We can easily implement Asynchronous using 'async' and 'await' keywords. A new Thread()is not dealing with Thread pool thread, whereas Task does use thread pool thread.
StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.
Well, this works:
class Program { static void Main(string[] args) { var task = Task.Factory.StartNew(() => { Thread.CurrentThread.Name = "foo"; Thread.Sleep(10000); // Use Debug + Break to see it }); task.Wait(); } }
There's a problem however, the threadpool thread gets recycled and won't change its name. This can be confusing, you'll see it running later executing entirely different code. Be sure to take note of this. Your best bet is otherwise to use the Location column in the Debug + Windows + Threads window to find the task back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With