tags:

views:

73

answers:

3

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

+2  A: 

Hi,

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.

andyp
I think that is dangerous. You can only set the name on a thread once, but the threads that background workers use may be reused.
Jonathan Allen
I agree with @Jonathan - if it isn't your thread, you shouldn't be naming it.
Marc Gravell
A: 

You can name your threads in the "Threads"-window when you are debugging in Visual Studio.

Børge
A: 
public class NamedBackgroundWorker : BackgroundWorker
{
    public NamedBackgroundWorker(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }

    protected override void OnDoWork(DoWorkEventArgs e)
    {
        if (Thread.CurrentThread.Name == null) // Can only set it once
            Thread.CurrentThread.Name = Name;

        base.OnDoWork(e);
    }
}
I just checked with Reflector. BackgroundWorker.RunWorkerAsync uses thread-pool threads. Since a thread's name can only be set once, your code will throw an exception if you happen to use the same threadpool thread twice.
Jonathan Allen
.NET 4.0 uses a nested type "private delegate void WorkerThreadStartDelegate(object argument);"And they call BeginInvoke on it, so as far as I can see they don't use the ThreadPool, but you are correct, I should have checked if the Name was null before setting it.