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
2010-07-16 18:01:17
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
2010-07-18 10:55:05
I agree with @Jonathan - if it isn't your thread, you shouldn't be naming it.
Marc Gravell
2010-07-18 11:05:28
A:
You can name your threads in the "Threads"-window when you are debugging in Visual Studio.
Børge
2010-07-16 18:03:31
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
2010-07-18 11:01:07