代码如下
public int SendEmail()
{
string[] Address = new string[] { "1", "1", "1", "2" };
EmailModel model = new EmailModel();//一个实体类
for (int i = 0; i < Address.Count; i++)
{
Email eml = new Email(Address[i]);
Thread thread = new Thread(new ParameterizedThreadStart(eml.CountAdd));
thread.Start(model);
}
//这里执行方法等待所有线程执行完毕
return model.SuccessCount;
}
public void CoundAdd(object obj)
{
EmailModel model = obj as EmailModel;
lock (this)
{
if (successCount == "1")//successCount是通过构造函数传进来的参数
{
model.SuccessCount += 1;
}
}
}
model.SuccessCount最后的值为1,为什么会这样?应该为3吧
EmailModel model = new EmailModel();//一个实体类这个有问题
将model定义为全局的静态变量
private static EmailModel model = new EmailModel();
Lock()
程序不完整无法判断,猜测原因可能有二种
1.变量successCount程序运行中发生了变化
2.没有等待线程执行完毕