开发者

Access static method from static class from different threads. Is it safe?

开发者 https://www.devze.com 2023-03-14 13:17 出处:网络
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 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);
        }开发者_C百科


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消