Thursday, June 5, 2008

Event Handlers Are On Separate Threads

You know you are an engineer if you spend an hour arguing over something that can be tested in five minutes.

Below is some code from the Microsoft site that illustrates how to handle FileSystemWatcher events.

I added a few more write lines to report out the thread ids. This clearly shows the event handlers are occurring on separate threads. As an aside, this reinforces the 'bring on the cores' attitude to multicores, since applications tend to be multithreaded even the most simple of applications.


===Code Start===

public static void Main()
{
Watch();
}
public static void Watch()
{
string[] args = System.Environment.GetCommandLineArgs();
// If a directory is not specified, exit program.
if (args.Length != 2)
{
// Display the proper way to call the program.
Console.WriteLine("Usage: FileWatch.exe (directory)");
return;
}
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess NotifyFilters.LastWrite
NotifyFilters.FileName NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
//
Console.WriteLine("main thread: " + System.Threading.Thread.CurrentThread.GetHashCode());
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("OnChanged thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("OnCreated thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("OnDeleted thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("OnRenamed thread: " + System.Threading.Thread.CurrentThread.ManagedThreadId);
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}

No comments: