Is it possible for a constructor to be pre-empted in C#?
For example, consider the code:
public class A
{
public bool ready = true;
public A()
{
ready = false; // Point #1
// Other initialization stuff
ready = true; // Point #2
}
}
Somewhere else in the code two threads have access to a variable of type A, the first thread calls the constructor which is pre-empted at point #1. Then the second thread tests for ready
and finds it to still be true therefore it does something bad.
Is this scenario possible?
More specifically:
- Can a constructor be pre-empted?
- If so, does this mean that there should be synchronization code such as
lock
in the constructor? - Is the object being constructed only assigned to the shared variable after the constructor exits, thereby avoiding the question altogether?