Specifying a Thread's Name when using Task.StartNew

20,395

Solution 1

Not a Thread-name for sure.

Threads and tasks are not 1-to-1 related.

You can use the Task.Id to track it.

Solution 2

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.

Solution 3

I prefer to use Thread.CurrentThread.ManagedThreadId. It's not as good as a name, but does help track the specific work for a thread.

Share:
20,395
Jon
Author by

Jon

Updated on April 22, 2020

Comments

  • Jon
    Jon about 4 years

    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??);