Here is my single-thread code :
OnStart
{
FileSystemWatcher Watcher = new FileSystemWatcher();
Watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite |NotifyFilters.CreationTime | NotifyFilters.DirectoryName;
FileActionHandler ActionHandler = new FileActionHandler();
Watcher.Created += new FileSystemEventHandler(ActionHandler.onCreate);
}
onCreate(object source,FileSystemEventArgs e)
{
try
{
FileInfo file = new FileInfo (e.FullPath);
String output = <FileName>File.Name + <FullPath>File.FullName + <FileSize>File.Length + <CreationTime>File.CreationTime + <LastAccess>File.LastAccess + <LastWriteTime>File.LastWriteTime;
LogToTextFile(output);
}
catch
{
LogToTextFile(ex.GetBaseException().Message);
}
}
private void LogToTextFile(String s)
{
FileStream fileStream = new FileStream(@"c:\Log.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fileStream.Close();
}
Question: I want to incorporate Multi-Threading for Event-Handling in C# ? Simply,what I mean is to start a new thread to handle for each of the events raised.
How do I go about doing that ? Please help me on this pressing issue…
If you’re not using .NET 4, as Pierre-Luc mentioned, you can simply swap out his code for this:
Or, if you would rather use a ThreadPool (which I would recommend in this case)…