Skip to content

Setting Thread.Name before Start() not working on macOS #106464

@NinoFloris

Description

@NinoFloris

Description

According to thread.cpp on macOS Thread.Name changes can only be done from the calling thread, which is fine. However this means that the fairly common pattern of newing up a thread with a descriptive name doesn't work as expected.

Observing certain dotnet threads vs rust etc. is more tedious as the name is entirely absent, requiring manual stack inspection and making a guess. A good example is the I/O threads:

var thread = new Thread(static s => ((SocketAsyncEngine)s!).EventLoop())
{
IsBackground = true,
Name = ".NET Sockets"
};
which show up unnamed when doing a simple process sampling.

The workaround is to move the name initialization into the start callback, but it seems the proper fix would be for the macOS PAL to set the name (if any) before calling into the start callback.

Reproduction Steps

var mres = new ManualResetEventSlim();
var thread = new Thread(() =>
{
    // This works
    // Thread.CurrentThread.Name = "Test thread name";
    mres.Wait();
}) { Name = "Test thread name " }; // this doesn't
thread.Start();
while (!Debugger.IsAttached)
    Thread.Sleep(1000);

Run this code in a console app and check the thread names. Easiest way to do so (unfortunately) is to open Activity Monitor -> select your process -> click the (...) ∨ button near the CPU | Memory | etc tab bar in the top, and click "Sample Process" to get a list of threads and stacks.

Expected behavior

new Thread { Name = "Test thread name" } correctly shows "Test thread name" in the sampled threads.

Actual behavior

new Thread { Name = "Test thread name" } does not show the name in the sampled threads, instead it has to be set inside the thread before it takes effect.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions