Cri*_*nSO 6 .net c# multithreading thread-safety
我有一个方法,如:
private static string AmpRemove(string str)
{
int index = str.IndexOf('&');
if (index > 0)
str = str.Substring(0, index);
return str;
}
Run Code Online (Sandbox Code Playgroud)
在这里,我试图从字符串中获取文本,直到&找到字符.我的大四学生修改了这个方法
private static string AmpRemove(string str)
{
if (str.IndexOf('&') > 0)
str = str.Substring(0, str.IndexOf('&'));
return str;
}
Run Code Online (Sandbox Code Playgroud)
所以不是存储它index,而是计算它两次,他的推理是因为该方法将在多个线程中调用,所以可能存储无效值index.
我的线程的理解是有限的,但我相信每个线程将有它自己的堆栈,其中参数str和index将被推动.我已经尝试过与他进行推理,这是一个可重入的代码,并且多线程无法修改此方法中的局部变量.
所以,我的问题是,我是否正确地假设缓存存储index是一个更好的解决方案,因为它不会涉及计算索引两次,因为它是局部变量并且str是方法的本地参数,所以多线程无法修改/更改str和index?
那是对的吗 ?