This is my first time working with threads, so I am really confused as to why the Thread.CurrentThread.Name
contains a value of null
. I want each specific thread to have a timer of its own, and wanted to first test if each thread is executing the OnElapsed
method. However, the thread name seems to be null
when I debugged it using Visual Studio. Any help would be appreciated.
public class Sample {
static System.Timers.Timer myTimer = new System.Timers.Timer();
static int i = 0;
public static void Main()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\Documents";
watcher.NotifyFilter = NotifyFilters.LastWrite;
Thread.CurrentThread.Name = "main";
watcher.Filter = "*.txt";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
private static void OnElapsed(object source, ElapsedEventArgs e)
{
Console.WriteLine(Thread.CurrentThread.Name); //<-- why is this null?
myTimer.Enabled = false;
Console.WriteLine(e.SignalTime);
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
FileSystemWatcher t = source as FileSystemWatcher;
t.EnableRaisingEvents = false;
string path = e.FullPath;
Thread t1 = new Thread( () => Print(path));
t1.Name = "Thread " + i;
i++;
t1.IsBackground = true;
t1.Start();
t.EnableRaisingEvents = true;
}
static void Print(string source)
{
string xmlFilePath = "xmlBasic.xml";
string timeout;
string path = Path.GetDirectoryName(source);
List<string> wordList = new List<string>();
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath);
XmlNode timeouts;
XmlElement root = doc.DocumentElement;
timeouts = root.SelectSingleNode("descendant::paths[directory='" + path + "']");
timeout = timeouts.LastChild.InnerText;
myTimer.Interval = int.Parse(timeout);
myTimer.Elapsed += new ElapsedEventHandler(OnElapsed);
myTimer.Enabled = true;
}
}
Thanks in advance!