Robert Robert - 1 month ago 13
C# Question

Naming BackgroundWorker

I would like to be able to name a BackgroundWorker to make it easier to debug. Is this possible?

Answer

I'd have to try but can't you just set the Name of the thread in the DoWork() method executed by the BackgroundWorker?

UPDATE: I just tried the following line of code as the first statement of my BackgroundWorkers DoWork() method and it works:

if (Thread.CurrentThread.Name == null)
    Thread.CurrentThread.Name = "MyBackgroundWorkerThread";

UPDATE: As Jonathan Allen correctly stated the name of a thread is write once, so I added a null check before setting the name. An attempt to write the name for the second time would result in an InvalidOperationException. As Marc Gravell wrote it might also make debugging harder as soon as pooled background threads are re-used for other work, so name threads only if necessary..

Comments