Will lock prevent changes done via reflection
Assume a class SomeClass
with private static
field like this. The access to this field is synchronized using lock
.
private static SomeClass _instance
private static object _sync = new object();
public static SomeClass Instance
get
lock (_sync)
if (_instance == null)
_instance = Create();
return _instance;
When another code from different thread will try to set the value of this variable to e.g. null
using reflection, will the lock
prevent this and let the reflection call wait until the lock was released?
E.g. something like this:
Type type = typeof(SomeClass);
string fieldName = "_instance";
object value = null;
FieldInfo field = type.GetField(fieldName, true);
field.SetValue(null, value);
c# reflection locking
|
show 2 more comments
Assume a class SomeClass
with private static
field like this. The access to this field is synchronized using lock
.
private static SomeClass _instance
private static object _sync = new object();
public static SomeClass Instance
get
lock (_sync)
if (_instance == null)
_instance = Create();
return _instance;
When another code from different thread will try to set the value of this variable to e.g. null
using reflection, will the lock
prevent this and let the reflection call wait until the lock was released?
E.g. something like this:
Type type = typeof(SomeClass);
string fieldName = "_instance";
object value = null;
FieldInfo field = type.GetField(fieldName, true);
field.SetValue(null, value);
c# reflection locking
2
the answer here is simply: no
– Daniel A. White
Nov 15 '18 at 15:25
this is a social-engineering problem - catch bad behavior in code reviews.
– Daniel A. White
Nov 15 '18 at 15:25
I think this question at least deserves an answer elaborating on the "why?", the technical, CLR-related reason. Documentation only says, "avoid using the following as lock objects: Type instances, as those might be obtained by thetypeof
operator or reflection" and that's not what OP does.
– dlatikay
Nov 15 '18 at 15:37
lock
is collaborative. All code accessing the same protected resources has to be written to follow whatever locking rules you're trying to establish. If someone else writes code that accesses the protected resource(s) but doesn't follow your locking convention, nothing prevents that. How did you imagine that anything else would know, specifically, that_sync
and_instance
are related?
– Damien_The_Unbeliever
Nov 15 '18 at 17:44
1
@dee - it's got nothing to do with reflection. If you write another method in this class that accesses the same resource and fails to use the same lock object, that would also compile and run fine and race the same issues
– Damien_The_Unbeliever
Nov 15 '18 at 19:03
|
show 2 more comments
Assume a class SomeClass
with private static
field like this. The access to this field is synchronized using lock
.
private static SomeClass _instance
private static object _sync = new object();
public static SomeClass Instance
get
lock (_sync)
if (_instance == null)
_instance = Create();
return _instance;
When another code from different thread will try to set the value of this variable to e.g. null
using reflection, will the lock
prevent this and let the reflection call wait until the lock was released?
E.g. something like this:
Type type = typeof(SomeClass);
string fieldName = "_instance";
object value = null;
FieldInfo field = type.GetField(fieldName, true);
field.SetValue(null, value);
c# reflection locking
Assume a class SomeClass
with private static
field like this. The access to this field is synchronized using lock
.
private static SomeClass _instance
private static object _sync = new object();
public static SomeClass Instance
get
lock (_sync)
if (_instance == null)
_instance = Create();
return _instance;
When another code from different thread will try to set the value of this variable to e.g. null
using reflection, will the lock
prevent this and let the reflection call wait until the lock was released?
E.g. something like this:
Type type = typeof(SomeClass);
string fieldName = "_instance";
object value = null;
FieldInfo field = type.GetField(fieldName, true);
field.SetValue(null, value);
c# reflection locking
c# reflection locking
edited Nov 15 '18 at 15:24
dee
asked Nov 15 '18 at 15:20
deedee
10.6k32445
10.6k32445
2
the answer here is simply: no
– Daniel A. White
Nov 15 '18 at 15:25
this is a social-engineering problem - catch bad behavior in code reviews.
– Daniel A. White
Nov 15 '18 at 15:25
I think this question at least deserves an answer elaborating on the "why?", the technical, CLR-related reason. Documentation only says, "avoid using the following as lock objects: Type instances, as those might be obtained by thetypeof
operator or reflection" and that's not what OP does.
– dlatikay
Nov 15 '18 at 15:37
lock
is collaborative. All code accessing the same protected resources has to be written to follow whatever locking rules you're trying to establish. If someone else writes code that accesses the protected resource(s) but doesn't follow your locking convention, nothing prevents that. How did you imagine that anything else would know, specifically, that_sync
and_instance
are related?
– Damien_The_Unbeliever
Nov 15 '18 at 17:44
1
@dee - it's got nothing to do with reflection. If you write another method in this class that accesses the same resource and fails to use the same lock object, that would also compile and run fine and race the same issues
– Damien_The_Unbeliever
Nov 15 '18 at 19:03
|
show 2 more comments
2
the answer here is simply: no
– Daniel A. White
Nov 15 '18 at 15:25
this is a social-engineering problem - catch bad behavior in code reviews.
– Daniel A. White
Nov 15 '18 at 15:25
I think this question at least deserves an answer elaborating on the "why?", the technical, CLR-related reason. Documentation only says, "avoid using the following as lock objects: Type instances, as those might be obtained by thetypeof
operator or reflection" and that's not what OP does.
– dlatikay
Nov 15 '18 at 15:37
lock
is collaborative. All code accessing the same protected resources has to be written to follow whatever locking rules you're trying to establish. If someone else writes code that accesses the protected resource(s) but doesn't follow your locking convention, nothing prevents that. How did you imagine that anything else would know, specifically, that_sync
and_instance
are related?
– Damien_The_Unbeliever
Nov 15 '18 at 17:44
1
@dee - it's got nothing to do with reflection. If you write another method in this class that accesses the same resource and fails to use the same lock object, that would also compile and run fine and race the same issues
– Damien_The_Unbeliever
Nov 15 '18 at 19:03
2
2
the answer here is simply: no
– Daniel A. White
Nov 15 '18 at 15:25
the answer here is simply: no
– Daniel A. White
Nov 15 '18 at 15:25
this is a social-engineering problem - catch bad behavior in code reviews.
– Daniel A. White
Nov 15 '18 at 15:25
this is a social-engineering problem - catch bad behavior in code reviews.
– Daniel A. White
Nov 15 '18 at 15:25
I think this question at least deserves an answer elaborating on the "why?", the technical, CLR-related reason. Documentation only says, "avoid using the following as lock objects: Type instances, as those might be obtained by the
typeof
operator or reflection" and that's not what OP does.– dlatikay
Nov 15 '18 at 15:37
I think this question at least deserves an answer elaborating on the "why?", the technical, CLR-related reason. Documentation only says, "avoid using the following as lock objects: Type instances, as those might be obtained by the
typeof
operator or reflection" and that's not what OP does.– dlatikay
Nov 15 '18 at 15:37
lock
is collaborative. All code accessing the same protected resources has to be written to follow whatever locking rules you're trying to establish. If someone else writes code that accesses the protected resource(s) but doesn't follow your locking convention, nothing prevents that. How did you imagine that anything else would know, specifically, that _sync
and _instance
are related?– Damien_The_Unbeliever
Nov 15 '18 at 17:44
lock
is collaborative. All code accessing the same protected resources has to be written to follow whatever locking rules you're trying to establish. If someone else writes code that accesses the protected resource(s) but doesn't follow your locking convention, nothing prevents that. How did you imagine that anything else would know, specifically, that _sync
and _instance
are related?– Damien_The_Unbeliever
Nov 15 '18 at 17:44
1
1
@dee - it's got nothing to do with reflection. If you write another method in this class that accesses the same resource and fails to use the same lock object, that would also compile and run fine and race the same issues
– Damien_The_Unbeliever
Nov 15 '18 at 19:03
@dee - it's got nothing to do with reflection. If you write another method in this class that accesses the same resource and fails to use the same lock object, that would also compile and run fine and race the same issues
– Damien_The_Unbeliever
Nov 15 '18 at 19:03
|
show 2 more comments
1 Answer
1
active
oldest
votes
No, lock will not prevent any access that does not go through locking the same resource. Since reflection will not go through lock
, you will get race conditions.
Here is (slightly different from your code but nontheless doing same thing) what I mean→
void SetOne()
lock (_sync)
critical_element = SOME_VALUE;
void SetTwo()
critical_element = SOME_ANOTHER_VALUE;
Above definitely has race conditions.
Here is my understanding behind the OP's question. I think OP wants to use Singleton
pattern and here is a very nice and thread safe implementation. You do not need to deal with locks either. However, some bad users might still set the backing field using reflection.
public sealed class Singleton
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance get return lazy.Value;
private Singleton()
Thank you for your answer! I understood that the lock is effective only for calls which go through the normal access, but with reflection there the value is changed directly. That was my question, I was not sure, how the locking works. The singleton with Lazy of T is cool, thanks as well.
– dee
Nov 19 '18 at 19:41
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53322601%2fwill-lock-prevent-changes-done-via-reflection%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
No, lock will not prevent any access that does not go through locking the same resource. Since reflection will not go through lock
, you will get race conditions.
Here is (slightly different from your code but nontheless doing same thing) what I mean→
void SetOne()
lock (_sync)
critical_element = SOME_VALUE;
void SetTwo()
critical_element = SOME_ANOTHER_VALUE;
Above definitely has race conditions.
Here is my understanding behind the OP's question. I think OP wants to use Singleton
pattern and here is a very nice and thread safe implementation. You do not need to deal with locks either. However, some bad users might still set the backing field using reflection.
public sealed class Singleton
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance get return lazy.Value;
private Singleton()
Thank you for your answer! I understood that the lock is effective only for calls which go through the normal access, but with reflection there the value is changed directly. That was my question, I was not sure, how the locking works. The singleton with Lazy of T is cool, thanks as well.
– dee
Nov 19 '18 at 19:41
add a comment |
No, lock will not prevent any access that does not go through locking the same resource. Since reflection will not go through lock
, you will get race conditions.
Here is (slightly different from your code but nontheless doing same thing) what I mean→
void SetOne()
lock (_sync)
critical_element = SOME_VALUE;
void SetTwo()
critical_element = SOME_ANOTHER_VALUE;
Above definitely has race conditions.
Here is my understanding behind the OP's question. I think OP wants to use Singleton
pattern and here is a very nice and thread safe implementation. You do not need to deal with locks either. However, some bad users might still set the backing field using reflection.
public sealed class Singleton
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance get return lazy.Value;
private Singleton()
Thank you for your answer! I understood that the lock is effective only for calls which go through the normal access, but with reflection there the value is changed directly. That was my question, I was not sure, how the locking works. The singleton with Lazy of T is cool, thanks as well.
– dee
Nov 19 '18 at 19:41
add a comment |
No, lock will not prevent any access that does not go through locking the same resource. Since reflection will not go through lock
, you will get race conditions.
Here is (slightly different from your code but nontheless doing same thing) what I mean→
void SetOne()
lock (_sync)
critical_element = SOME_VALUE;
void SetTwo()
critical_element = SOME_ANOTHER_VALUE;
Above definitely has race conditions.
Here is my understanding behind the OP's question. I think OP wants to use Singleton
pattern and here is a very nice and thread safe implementation. You do not need to deal with locks either. However, some bad users might still set the backing field using reflection.
public sealed class Singleton
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance get return lazy.Value;
private Singleton()
No, lock will not prevent any access that does not go through locking the same resource. Since reflection will not go through lock
, you will get race conditions.
Here is (slightly different from your code but nontheless doing same thing) what I mean→
void SetOne()
lock (_sync)
critical_element = SOME_VALUE;
void SetTwo()
critical_element = SOME_ANOTHER_VALUE;
Above definitely has race conditions.
Here is my understanding behind the OP's question. I think OP wants to use Singleton
pattern and here is a very nice and thread safe implementation. You do not need to deal with locks either. However, some bad users might still set the backing field using reflection.
public sealed class Singleton
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance get return lazy.Value;
private Singleton()
answered Nov 16 '18 at 8:00
Hasan Emrah SüngüHasan Emrah Süngü
1,698422
1,698422
Thank you for your answer! I understood that the lock is effective only for calls which go through the normal access, but with reflection there the value is changed directly. That was my question, I was not sure, how the locking works. The singleton with Lazy of T is cool, thanks as well.
– dee
Nov 19 '18 at 19:41
add a comment |
Thank you for your answer! I understood that the lock is effective only for calls which go through the normal access, but with reflection there the value is changed directly. That was my question, I was not sure, how the locking works. The singleton with Lazy of T is cool, thanks as well.
– dee
Nov 19 '18 at 19:41
Thank you for your answer! I understood that the lock is effective only for calls which go through the normal access, but with reflection there the value is changed directly. That was my question, I was not sure, how the locking works. The singleton with Lazy of T is cool, thanks as well.
– dee
Nov 19 '18 at 19:41
Thank you for your answer! I understood that the lock is effective only for calls which go through the normal access, but with reflection there the value is changed directly. That was my question, I was not sure, how the locking works. The singleton with Lazy of T is cool, thanks as well.
– dee
Nov 19 '18 at 19:41
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53322601%2fwill-lock-prevent-changes-done-via-reflection%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
the answer here is simply: no
– Daniel A. White
Nov 15 '18 at 15:25
this is a social-engineering problem - catch bad behavior in code reviews.
– Daniel A. White
Nov 15 '18 at 15:25
I think this question at least deserves an answer elaborating on the "why?", the technical, CLR-related reason. Documentation only says, "avoid using the following as lock objects: Type instances, as those might be obtained by the
typeof
operator or reflection" and that's not what OP does.– dlatikay
Nov 15 '18 at 15:37
lock
is collaborative. All code accessing the same protected resources has to be written to follow whatever locking rules you're trying to establish. If someone else writes code that accesses the protected resource(s) but doesn't follow your locking convention, nothing prevents that. How did you imagine that anything else would know, specifically, that_sync
and_instance
are related?– Damien_The_Unbeliever
Nov 15 '18 at 17:44
1
@dee - it's got nothing to do with reflection. If you write another method in this class that accesses the same resource and fails to use the same lock object, that would also compile and run fine and race the same issues
– Damien_The_Unbeliever
Nov 15 '18 at 19:03