Multithreading 线程安全方法调用
请让我知道下面的方法调用是否是线程安全的。 我在我的主线程上调用ThreadStartMain,创建新线程,并在新实例上调用_getConcurryName方法 因为我总是通过新实例调用,所以我认为这是线程安全的,即使在某些类中有实例变量Multithreading 线程安全方法调用,multithreading,object,thread-safety,c#-3.0,Multithreading,Object,Thread Safety,C# 3.0,请让我知道下面的方法调用是否是线程安全的。 我在我的主线程上调用ThreadStartMain,创建新线程,并在新实例上调用_getConcurryName方法 因为我总是通过新实例调用,所以我认为这是线程安全的,即使在某些类中有实例变量 class MyThread { private void ThreadStartMain() { for (int i = 0; i < 5; i++) {
class MyThread
{
private void ThreadStartMain()
{
for (int i = 0; i < 5; i++)
{
A a = new A();
ThreadStart start = new ThreadStart(a.A_GetCounryName);
Thread t = new Thread(start);
t.Start();
}
}
}
class A
{
public B GetNewObject()
{
B bObj = new B();
return bObj;
}
public void A_GetCounryName()
{
B b=GetObject();
string cName=b.B_GetCoutryName();
}
}
class B
{
C cObj = null;
public B()
{
cObj = new C();
cObj.Prop1 = 1;
cObj.Prop1 = 2;
cObj.Prop1 = 3;
}
public string B_GetCoutryName()
{
string countryName= cObj.C_GetCoutryName();
return countryName;
}
}
class C
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
public int Prop3 { get; set; }
public string C_GetCoutryName()
{
string name = "Italy";
return name;
}
}
类读取
{
私有void ThreadStartMain()
{
对于(int i=0;i<5;i++)
{
A=新的A();
ThreadStart=新的ThreadStart(a.a_getconcurryname);
螺纹t=新螺纹(开始);
t、 Start();
}
}
}
甲级
{
公共B GetNewObject()
{
B bObj=新的B();
返回bObj;
}
public void A_GetCounryName()
{
B=GetObject();
字符串cName=b.bu GetCoutryName();
}
}
B类
{
C cObj=null;
公共图书馆B()
{
cObj=新的C();
cObj.Prop1=1;
cObj.Prop1=2;
cObj.Prop1=3;
}
公共字符串B_GetCoutryName()
{
字符串countryName=cObj.C_GetCoutryName();
返回国家名称;
}
}
C类
{
公共int Prop1{get;set;}
公共int Prop2{get;set;}
公共int Prop3{get;set;}
公共字符串C_GetCoutryName()
{
string name=“意大利”;
返回名称;
}
}
是的,这是安全的,因为您的线程不共享状态。更准确地说:它们不访问公共存储位置。这是因为我总是创建新实例并访问其方法。是的。每个新实例都有自己的数据,独立于所有其他实例。