String 类中的线程安全 [英] Thread safety in String class

查看:41
本文介绍了String 类中的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用String 类从局部变量构建字符串是否线程安全,就像下面的方法一样?假设下面的方法是从多个线程调用的.

Is it thread safe to build strings from local variables using the String class like in the methods below? Suppose that the methods below are called from several threads.

public static string WriteResult(int value, string name)
{
    return string.Format("Result: value={0} name={1}", value, name);
}

public static string WriteResult2(int value, string name)
{
    return "Result: value=" + value + " name=" + name;
}

还是需要使用StringBuilder来保证线程安全?

Or do I need to use StringBuilder to ensure thread safety?

推荐答案

那绝对没问题.除了字符串文字之外,在任何一段代码中都没有共享状态.由于字符串是不可变的,因此可以在线程之间自由共享字符串,并且 string.Formatstring.Concat(在第二段代码中隐式调用)都是线程安全.

That's absolutely fine. There is no shared state in either piece of code other than the string literals. As strings are immutable, it's fine for strings to be shared freely between threads, and both string.Format and string.Concat (implicitly called in the second piece of code) are thread-safe.

即使其中一个参数是可变的,即使该方法改变了参数,例如

Even if one of the parameters were mutable and even if the method mutated the parameters, e.g.

public static void AddResult(int value, List<string> results)
{
    results.Add("Value " + value);
}

...那么方法本身仍然是线程安全的,只要多个线程不引用相同的List.如果多个线程确实引用了同一个List,那么即使它只是从列表中读取,作为另一个线程也是不安全的可能正在改变它.

... then the method itself would still be thread-safe, so long as multiple threads didn't refer to the same List<string>. If multiple threads did refer to the same List<string> then it would be unsafe even if it just read from the list, as another thread could be mutating it.

这篇关于String 类中的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆