从不同线程访问静态类的静态方法。安全吗?
我使用 FileSystemWatcher 监视文件夹以从中删除指定的文件。当引发 FileSystemWatcher 事件时,我创建新线程来删除文件。我的代码线程安全吗? 我不确定从线程访问的静态 Log 方法。
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码是线程安全的。
但这与
静态
方法没有太大关系,而是与方法的作用有关。您的
Log
方法仅调用Console.WriteLine
根据 MSDN,它本身是线程安全的。简而言之:将方法设置为
静态
并不会自动使其成为线程安全的。但是:.NET Framework 中的大多数静态方法都是线程安全实现的。
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 callsConsole.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.您的问题基本上是,
线程是否安全?
答案在这里: 从多个线程调用 Console.WriteLine (是
)然而,可能会导致一些竞争条件。
您可能会收到多个调用。
另一件事是,如果您的事件快速触发,导致许多异常,
Your question is basically, whether or not
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
calls in case your event will fire rapidly, causing many exceptions.