I'm not clear on the process that CLR performs when running a program. I'm not quite clear on when to use lock() or some other type of thread safe objects.
Please help me understand the following:
Having this code:
public class Person {
string Name {get;set;}
}
public class Calc {
public string DoStuff(Person p){
// perform some processing on person object
// maybe call external API and update person object
}
}
Please correct me if I'm wrong but this is my understanding of Example 1. In single threaded app (suppose it's a mvc application and I'm using DI and already registered "Service" in the container.
I call Service.Work() from somewhere in my application. new Calc() is created (CLR allocates this object in memory) and Calc.DoStuff() does computation on Person object. Since before the call new Calc() is created and get called from two browsers they are in separate execution paths. Is this correct?
// Example 1
public class Service {
public void Work(person) {
var calc = new Calc();
string test = calc.DoStuff(person);
}
}
// Example 2
public class Service {
public Service() {
var calc = new Calc(); // this is different
}
public void Work(person) {
string test = calc.DoStuff(person);
}
}
Now what happens in the same scenario, however this time at the time of allocating Service in memory Calc is instantiated in the Service's constructor. Would that cause problems with to simultaneous calls to Work() (since there is only ONE instance of Calc? object.
Here is where your intuition went wrong:
Now what happens in the same scenario, however this time at the time of allocating Service in memory Calc is instantiated in the Service's constructor. Would that cause problems with to simultaneous calls to Work() (since there is only ONE instance of Calc? object.
Each call to the Service function has its own thread stack, and thus separate copies of all local variables.
For all intents and purposes, just picture the two browser requests as two totally separate programs.
一般来说,在这两种情况下,你不应该期望 Calc 的实例是单一的(singleton),所以你的 DoStuff 方法需要有某种同步,比如lock(p)
,例如,如果类 Person 的实例是相同的所有通话。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.