0

I have monitoring a folder using FileSystemWatcher to delete specified files from it. When FileSystemWatcher event is raised I create new thread to delete file. Is my code thread safe? I am not sure about static Log method which is accessed from Threads.

FileSystemWatcher.EventRaised....
{
   var delFolder = Path.GetDirectoryName(e.FullPath);
   var t = new Thread(DeleteThread.Do);
   t.Start(delFolder);
}
/*..code skip...*/



 static class DeleteThread
        {

            public static void Do(object delFolder)
            {
                try
                {
                    Log("Deleting folder {0}", (string)delFolder);
                    Directory.Delete((string)delFolder, true);
                }
                catch (Exception e)
                {
                    Log("Error deleting folder {0}. {1}", (string)delFolder, e.Message);
                }
            }
        }

        private static void Log(string text, string text1 = "", string text2 = "", string text3 = "")
        {
            Console.WriteLine(text, text1, text2, text3);
        }
Tomas
  • 17,551
  • 43
  • 152
  • 257

2 Answers2

2

Your code is thread safe.
But this hasn't much to do with static methods, but with what the methods do.
Your Log method only calls Console.WriteLine which itself is thread safe according to the MSDN.

In short: Making a method static doesn't make it thread safe automatically.
But: Most static methods in the .NET Framework are implemented thread safe.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

Your question is basically, whether or not

Console.WriteLine("")

is thread-safe or not? The answer is here: Calling Console.WriteLine from multiple threads (YES)

It could cause you some race conditions, however. Another thing, you could get multiple

   Directory.Delete()

calls in case your event will fire rapidly, causing many exceptions.

Community
  • 1
  • 1
DiVan
  • 381
  • 2
  • 6
  • Unique folder will be passed to Directory.Delete() method, so I do not see any problems here. – Tomas Jun 21 '11 at 09:30
  • What about nested folders? Multiple FileWatchers? That's why it "you **could** get". – DiVan Jun 21 '11 at 09:42
  • That's right but I haven't explained that in my situation I have only top level folders without sub-folders. In general you are right! – Tomas Jun 21 '11 at 13:52