Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a Thread's Name when using Task.StartNew

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??); 
like image 778
Jon Avatar asked Nov 07 '11 15:11

Jon


People also ask

What is the difference between task run and task factory StartNew?

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!

Does Task create new thread?

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.

What does task factory StartNew do?

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.


1 Answers

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.

like image 78
Hans Passant Avatar answered Oct 02 '22 13:10

Hans Passant