开发者

Can a string declared outside a lock and used within a lock be changed by another thread?

开发者 https://www.devze.com 2023-04-02 05:28 出处:网络
Is the following co开发者_StackOverflow社区de thread-safe? I assume it is because strings are immutable. (Code thrown together for demo purposes)

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.

0

精彩评论

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