Is the following co开发者_StackOverflow社区de thread-safe? I assume it is because strings are immutable. (Code thrown together for demo purposes)
static readonly object _lockObject = new object();
void SomeMethod(string filePath, string fileName)
{
// Any reason for this to be moved inside the lock?
string s = Path.Combine(filePath, fileName);
lock (_lockObject)
{
try
{
// Other stuff to create the file here.
}
finally
{
File.Delete(s);
}
}
}
I'm curious after reading this (first few lines of the section Locking and Atomicity).
Yes, it's thread-safe.
Even removing the lock would make it thread safe :-)
You're only using local variables and static BCL methods (which are always thread-safe).
Strings are immutable so they will never change after being constructed. and since you're local is not passed by ref anywhere the reference won't change either so it safe
It's thread-safe, but any exception thrown by File.Delete
will replace the real exception when the stack unwinds.
精彩评论