Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is ContextStaticAttribute?

Tags:

c#

.net

From the documentation:

A static field marked with ContextStaticAttribute is not shared between contexts. If the indicated static field is accessed on a different context, it will contain a different value. Use this attribute as it is, and do not derive from it.

The following example shows the syntax of this attribute:

[ContextStatic]
static int f=7;

Unfortunately it does not clarify what is meant by "context" in this case. Can someone give an example for when this attribute would be used?

like image 312
Knaģis Avatar asked Apr 10 '13 13:04

Knaģis


1 Answers

The attribute matters in a case where you use remoting, like a class derived from MarshalByRefObject. Your code is then working with a proxy in the client program, a fake class object that looks exactly like the original class but whose methods are implemented by the CLR and serialize the method arguments across to the actual object that runs on the server. Typically on another machine.

Fields are a problem in such a class, they cannot be faked with a substitute method. This is something that the jitter deals with. When it detects access to a field in a MRBO object then it doesn't generate the code to read/write the field directly, it calls a helper method in the CLR instead. Which knows whether the object is a proxy or the real object and either directly returns the field value or makes a remoting call instead.

This adds overhead of course, an issue with a static field that can be accessed very frequently. The [ContextStatic] attribute says that you don't care about having the actual static field value, the local copy of it is good enough. Or it can be used intentionally if for some reason keeping track of state locally is important. I can't think of a good example of this. Nor did the framework programmers, it isn't used anywhere inside the framework code.

like image 92
Hans Passant Avatar answered Oct 01 '22 11:10

Hans Passant