Naming BackgroundWorker
I would like to be able to na开发者_如何学编程me a BackgroundWorker to make it easier to debug. Is this possible?
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..
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);
}
}
You can extend the background worker through a custom class:
`
public class NamedBackgroundWorker : BackgroundWorker
{
public string Name;
public BackgroundWorker(string Name)
{
this.Name = Name;
}
}
` Now just create an object from this and you can name it and use it as a background worker.
You can name your threads in the "Threads"-window when you are debugging in Visual Studio.
精彩评论