Is the following code 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).