When using an ObjectDataSource control, either instance methods or static methods can be used for the SelectMethodand SelectCountMethod. According to the MSDN documentation, if an instance method is used, a new instance will be created and disposed upon completion.
If it is an instance method, the business object is created and
destroyed each time the method that is specified by the SelectMethod
property is called.
However, according to this in-depth walkthrough, if paging is enabled and both the SelectMethod and SelectCountMethod are instance methods, the same instance is used when calling these methods.
If we have enabled paging and our SelectMethod and SelectCountMethod
are instance methods, the same instance is used when calling both
methods, so we can save the total number of registers in a field in
the SelectMethod and then we can return it in the SelectCountMethod.
In another reference, the information provided (apparently by a member of the MS ASP.NET team) contradicts the information above.
However you should realize that different instances are used to call
the Select and SelectCount method ...
My question: Which of these behaviors is the actual one implemented in asp.net? Is the same instance used when calling those methods, or are they called by different instances?
I have attempted (in .net 3.5 VS 2008) to implement paging using the first reference (which says they are called by the same instance), and it does work for me. When I set the record count into a non-static variable/field in the SelectMethod, the same value is indeed returned when SelectCountMethod is called. I suppose that should mean that the same instance is used, contrary to the information in the second reference, and that it would be safe for me to set the record count in the SelectMethod and return it in the SelectCountMethod using a non-static variable. However, I'd prefer if someone could actually confirm this, as the first reference is quite old (written in 06), and I have no way of testing if this behavior has been changed in newer versions (.net 4.0 and up).
Please let me know if my question is unclear, or if there is an official reference that can answer my question.
Related
The docs for Interlocked.Exchange<T> contain the following remark:
This method overload is preferable to the Exchange(Object, Object) method overload, because the latter requires late-bound access to the destination object.
I am quite bewildered by this note. To me "late binding" refers to runtime method dispatch and doesn't seem to have anything to do with the technical specifics of atomically swapping two memory locations. What is the note talking about? What does "late-bound access" mean in this context?
canton7's answer is correct, and thanks for the shout-out. I'd like to add a few additional points.
This sentence, as is too often the case in the .NET documentation, both chooses to enstructure bizarre word usements, and thoroughly misses the point. For me, the poor word choice that stood out was not "late bound", which merely misses the point. The really awful word choice is using "destination object" to mean variable. A variable is not an object, any more than your sock drawer is a pair of socks. A variable contains a reference to an object, just as a sock drawer contains socks, and those two things should not be confused.
As you note, the reason to prefer the T version has nothing to do with late binding. The reason to prefer the T version is C# does not allow variant conversions on ref arguments. If you have a variable shelly of type Turtle, you cannot pass ref shelly to a method that takes ref object, because that method could write a Tiger into a ref object.
What then are the logical consequences of using the Object-taking overload on shelly? There are only two possibilities:
We copy the value of shelly to a second variable of type Object, do the exchange, and then copy the new value back, and now our operation is no longer atomic, which was the whole point of calling the interlocked exchange.
We change shelly to be of type Object, and now we are in a non-statically-typed and therefore bug-prone world, where we cannot ever be sure that shelly still contains a reference to Turtle.
Since both of those alternatives are terrible, you should use the generic version because it allows the aliased variable to be of the correct type throughout the operation.
The equivalent remark for Interlocked.Exchange(object, object) is:
Beginning with .NET Framework 2.0, the Exchange<T>(T, T) method overload provides a type-safe alternative for reference types. We recommend that you call it instead of this overload.
Although I haven't heard it used in this way before, I think by "late-bound" it simply means "non type-safe", as you need to cast the object to your concrete type (at runtime) before using it.
As well as virtual method dispatch, "Late Binding" also commonly refers to reflection, as the exact method to be called similarly isn't known until runtime.
To quote Eric Lippert:
Basically by "early binding" we mean "the binding analysis is performed by the compiler and baked in to the generated program"; if the binding fails then the program does not run because the compiler did not get to the code generation phase. By "late binding" we mean "some aspect of the binding will be performed by the runtime" and therefore a binding failure will manifest as a runtime failure
(emphasis mine). Under this rather loose definition, casting object to a concrete type and then calling a method on it could be seen as "late bound", as there's an element of the binding which is performed at, and could fail at, runtime.
I stumbled upon a method today. I'm talking about: Array.Initialize().
According to the documentation:
This method is designed to help compilers support value-type arrays; most users do not need this method.
How does this method is responsible for making the compiler support value types? As far as I'm concerned this method just:
Initializes every element of the value-type Array by calling the default constructor of the value type.
Also, why is it public? I don't see myself with the need of calling this method, compilers already initialize arrays when created, so manually calling this method will be redundant and useless.
Even when my intention would be resetting the values of an array, I would still not call it, I would create a new one. array = new int[].
So, it seems that this method exist just for the sake of the compiler. Why is this? Can anyone give me some more details?
It's worth noting that the rules of .NET are different to the rules of C#.
There are things we can do in .NET that we can't do in C#, generally either because the code is not verifiable (ref return types for example) or because they could introduce some confusion.
In C# structs cannot have a defined parameterless constructor, and calling new SomeValueType() works by creating a zero-filled portion of memory (all fields therefore being 0 for numeric types, null for reference types, and the result of this same rule again for other value-types).
In .NET you can have a parameterless constructor on a value type.
It's probably a bad idea to do so. For one thing the rules about just when it is called and just when the memory of the value is zero-filled, and what happens upon assignment in different cases aren't entirely simple (e.g. new SomeValueType() will call it but new T() in a generic method where T is SomeValueType will not!). Life is simpler if the result of new SomeValueType() will always be zero-filling. That no doubt influenced the design of C# not allowing this even though .NET does.
For this reason, Array.Initialize() will never make sense on new arrays of any type that was written in C#, because calling the constructor and zero-filling is the same thing.
But by the same token, it's possible for a type to be written in another .NET language (at the very least, you can do it in CIL) that does have a parameterless constructor that actually has an effect. And for that reason its possible that a compiler for such a language would want its equivalent to new SomeValueType[3] to call that constructor on all the types in the array. And therefore it's sensible to have a method in the framework that allows such a fill to be done, so that a compiler for such a language can make use of it.
Also, why is it public?
So it can be called by code produced by such a hypothetical constructor even in a context where security restrictions prevent it from calling private methods of another assembly.
For me myself it looks like the Initialize() method runs through the array and recreates the Value Types within. So with a new array you get a new empty array and so you get with Array.Clear(), but with Array.Initialize() you get an Array full of fresh created Value Types (types and length based on the old array).
And that should be all of the difference.
Based on the CLR source, the method traverses each index of the array and initializes the value type on that index by calling the default constructor, similar to initobj IL instruction (I wonder what happens when the constructor throws an exception, though). The method is public because calling a private method directly from IL would make it a bit unverifiable.
Today's C# compilers do not initialize each element of the array when creating it, simply "set" each index to the default value of the type. C# 6 introduces implementing default constructors for value types (which were already supported by CLR), so this is needed for languages with different array creation semantics.
You can see the expected use in the test code:
https://github.com/dotnet/coreclr/blob/3015ff7afb4936a1c5c5856daa4e3482e6b390a9/tests/src/CoreMangLib/cti/system/array/arrayinitialize.cs
Basically, it sets an array of non-intrinsic value-types back to their default(T) state.
It does not seem like an amazingly useful tool, but I can see how it could be useful for zero'ing out arrays of non-intrinsic value data.
In one of the projects I take part in there is a vast use of WeakAction. That's a class that allows to keep reference to an action instance without causing its target not be garbage collected. The way it works is simple, it takes an action on the constructor, and keeps a weak reference to the action's target and to the Method but discards the reference to the action itself. When the time comes to execute the action, it checks if the target is still alive, and if so, invokes the method on the target.
It all works well except for one case - when the action is instantiated in a closure. consider the following example:
public class A
{
WeakAction action = null;
private void _register(string msg)
{
action = new WeakAction(() =>
{
MessageBox.Show(msg);
}
}
}
Since the lambda expression is using the msg local variable, the C# compiler auto generates a nested class to hold all the closure variables. The target of the action is an instance of the nested class instead of the instance of A. The action passed to the WeakAction constructor is not referenced once the constructor is done and so the garbage collector can dispose of it instantly. Later, if the WeakAction is executed, it will not work because the target is not alive anymore, even though the original instance of A is alive.
Now I can't change the way the WeakAction is called, (since it's in wide use), but I can change its implementation. I was thinking about trying to find a way to get access to the instance of A and to force the instance of the nested class to remain alive while the instance of A is still alive, but I don't know how to do get it.
There are a lot of questions about what A has to do with anything, and suggestions to change the way A creates a weak action (which we can't do) so here is a clarification:
An instance of class A wants an instance of class B to notify it when something happens, so it provides a callback using an Action object. A is not aware that B uses weak actions, it simply provides an Action to serve as callback. The fact that B uses WeakAction is an implementation detail that is not exposed. B needs to store this action and use it when needed. But B may live much longer then A, and holding a strong reference to a normal Action (which by itself holds a strong reference of the instance of A that generated it) causes A to never be garbage collected. If A is a part of a list of items that are no longer alive, we expect A to be garbage collected, and because of the reference that B holds of the Action, which by itself points to A, we have a memory leak.
So instead of B holding an Action that A provided, B wraps it into a WeakAction and stores the weak action only. When the time comes to call it, B only does so if theWeakAction is still alive, which it should be as long as A is still alive.
A creates that action inside a method and does not keep a reference to it on his own - that's a given. Since the Action was constructed in the context of a specific instance of A, that instance is the target of A, and when A dies, all weak references to it become null so B knows not to call it and disposes of the WeakAction object.
But sometimes the method that generated the Action uses variables defined locally in that function. In which case the context in which the action runs include not just the instance of A, but also the state of the local variables inside of the method (that is called a "closure"). The C# compiler does that by creating a hidden nested class to hold these variables (lets call it A__closure) and the instance that becomes the target of the Action is an instance of A__closure, not of A. This is something that the user should not be aware of. Except that this instance of A__closure is only referenced by the Action object. And since we create a weak reference to the target, and do not hold a reference to the action, there is no reference to the A__closure instance, and the garbage collector may (and usually does) dispose of it instantly. So A lives, A__closure dies, and despite the fact that A is still expecting the callback to be invoked, B can not do it.
That's the bug.
My question was if somebody knows of a way that the WeakAction constructor, the only piece of code that actually holds the original Action object, temporarily, can in some magic way extract the original instance of A from the A__closure instance that it finds in the Target of the Action. If so, I could perhaps extend A__Closure life cycle to match that of A.
After some more research and after collecting all the useful bits of information from the answers that were posted here, I realized that there is not going to be an elegant and sealed solution to the problem. Since this is a real life problem we went with the pragmatic approach, trying to at least reduce it by handling as many scenarios as possible, so I wanted to post what we did.
Deeper investigation of the Action object that is passed to the constructor of the WeakEvent, and especially the Action.Target property, showed that there are effectively 2 different cases of closure objects.
The first case is when the Lambda uses local variables from the scope of the calling function, but does not use any information from the instance of the A class. In the following example, assume EventAggregator.Register is a method that takes an action and stores a WeakAction that wraps it.
public class A
{
public void Listen(int num)
{
EventAggregator.Register<SomeEvent>(_createListenAction(num));
}
public Action _createListenAction(int num)
{
return new Action(() =>
{
if (num > 10) MessageBox.Show("This is a large number");
});
}
}
The lambda created here uses the num variable, which is a local variable defined in the scope of the _createListenAction function. So the compiler has to wrap it with a closure class in order maintain the closure variables. However, since the lambda does not access any of class A members, there is no need to store a reference to A. The target of the action will therefore not include any reference to the A instance and there is absolutely no way for the WeakAction constructor to reach it.
The second case is illustrated in the following example:
public class A
{
int _num = 10;
public void Listen()
{
EventAggregator.Register<SomeEvent>(_createListenAction());
}
public Action _createListenAction()
{
return new Action(() =>
{
if (_num > 10) MessageBox.Show("This is a large number");
});
}
}
Now _num is not provided as parameter to the function, it comes from the class A instance. Using reflection to learn about the structure of the Target object reveals that the last field the the compiler defines holds a reference to the A class instance. This case also applies when the lambda contains calls to member methods, as in the following example:
public class A
{
private void _privateMethod()
{
// do something here
}
public void Listen()
{
EventAggregator.Register<SomeEvent>(_createListenAction());
}
public Action _createListenAction()
{
return new Action(() =>
{
_privateMethod();
});
}
}
_privateMethod is a member function, so it is called in the context of the class A instance, so the closure must keep a reference to it in order to invoke the lambda in the right context.
So the first case is a Closure that only contains functions local variable, the second contains reference to the parent A instance. In both cases, there are no hard references to the Closure instance, so if the WeakAction constructor just leaves things the way they are, the WeakAction will "die" instantly despite the fact that the class A instance is still alive.
We are faced here with 3 different problems:
How to identify that the target of the action is a nested closure
class instance, and not the original A instance?
How to obtain a reference to the original class A instance?
How to extend the life span of the closure instance so that it lives
as long as the A instance live, but not beyond that?
The answer to the first question is that we rely on 3 characteristics of the closure instance:
- It is private (to be more accurate, it is not "Visible". When using C# compiler, the reflected type has IsPrivate set to true but with VB it does not. In all cases, the IsVisible property is false).
- It is nested.
- As #DarkFalcon mentioned in his answer, It is decorated with the [CompilerGenerated] attribute.
private static bool _isClosure(Action a)
{
var typ = a.Target.GetType();
var isInvisible = !typ.IsVisible;
var isCompilerGenerated = Attribute.IsDefined(typ, typeof(CompilerGeneratedAttribute));
var isNested = typ.IsNested && typ.MemberType == MemberTypes.NestedType;
return isNested && isCompilerGenerated && isInvisible;
}
While this is not a 100% sealed predicate (a malicious programmer may generate a nested private class and decorate it with the CompilerGenerated attribute), in real life scenarios this is accurate enough, and again, we are building a pragmatic solution, not an academic one.
So problem number 1 is solved. The weak action constructor identifies situations where the action target is a closure and responds to that.
Problem 3 is also easily solvable. As #usr wrote in his answer, once we get a hold of the A class instance, adding a ConditionalWeakTable with a single entry where the A class instance is the key and the closure instance is the target, solves the problem. The garbage collector knows not to collect the closure instance as long as the A class instance lives. So that's ok.
The only non - solvable problem is the second one, how to obtain a reference to the class A instance? As I said, there are 2 cases of closures. One where the compiler creates a member that holds this instance, and one where it doesn't. In the second case, there is simply no way to get it, so the only thing we can do is to create a hard reference to the closure instance in order to save it from being instantly garbage collected. This means that it may out live the class A instance (in fact it will live as long as the WeakAction instance lives, which may be forever). But this is not such a terrible case after all. The closure class in this case only contains a few local variables, and in 99.9% of the cases it is a very small structure. While this is still a memory leak, it is not a substantial one.
But just in order to allow users to avoid even that memory leak, we have now added an additional constructor to the WeakAction class, as follows:
public WeakAction(object target, Action action) {...}
And when this constructor is called, we add a ConditionalWeakTable entry where the target is the key and the actions target is the value. We also hold a weak reference to both the target and the actions target and if any of them die, we clear both. So that the actions target lives no less and no more than the provided target. This basically allows the user of the WeakAction to tell it to hold on to the closure instance as long as the target lives. So new users will be told to use it in order to avoid memory leaks. But in existing projects, where this new constructor is not used, this at least minimizes the memory leaks to closures that have no reference to the class A instance.
The case of closures that reference the parent are more problematic because they affect garbase collection. If we hold a hard reference to the closure, we cause a much more drastic memory leak becuase the class A instance will also never be cleared. But this case is also easier to treat. Since the compiler adds a last member that holds a reference to the class A instance, we simply use reflection to extract it and do exactly what we do when the user provides it in the constructor. We identify this case when the last member of the closure instance is of the same type as the declaring type of the closure nested class. (Again, its not 100% accurate, but for real life cases its close enough).
To summarize, the solution I presented here is not 100% sealed solution, simply because there does not seem to be a such solution. But since we have to provide SOME answer to this annoying bug, this solution at least reduces the problem substantially.
You want to extend the lifetime of the closure class instance to be exactly the same that the A instance has. The CLR has a special GC handle type for that: the Ephemeron, implemented as internal struct DependentHandle.
This struct is only exposed as part of the ConditionalWeakTable class. You could create one such table per WeakAction with exactly one item in it. The key would be an instance of A, the value would be the closure class instance.
Alternatively, you could pry open DependentHandle using private reflection.
Or, you could use one globally shared ConditionalWeakTable instance. It probably requires synchronization to use. Look at the docs.
Consider opening a connect issue to make DependentHandle public and link to this question to provide a use case.
a.Target provides access to the object which holds the lambda parameters. Performing a GetType on this will return the compiler-generated type. One option would be to check this type for the custom attribute System.Runtime.CompilerServices.CompilerGeneratedAttribute and keep a strong reference to the object in this case.
Now I can't change the way the WeakAction is called, (since it's in wide use) but I can change it's implementation. Note that this is the only way so far which can keep it alive without requiring modifications to how the WeakAction is constructed. It also doesn't attain the goal of keeping the lambda alive as long as the A object (it would keep it alive as long as the WeakAction instead). I do not believe that is going to be attainable without changing how the WeakAction is constructed as is done in the other answers. At a minimum, the WeakAction needs to obtain a reference to the A object, which you currently do not provide.
Assume that 2 different methods - one static and one non-static - need an instance variable.
The variable is used 3-5 different times within the methods for comparison purposes.
The variable is NOT changed in any manner.
Also would the type of variable - String, Colection, Collection, etc. make any difference on how it should be coded.
What is the best/right way of using Instance Variable within a private method (static and non-static)?
Pass as method argument
Store locally by using the method to get the value - this.getClaimPropertyVertices();
Store locally by getting the value - this.claimPropertyVertices;
Use the instance variable directly in the method
When creating a local variable to store the value will the "final" keyword provide any advantages, if the variable will not be changed.
Edit 1: Based on a comment, I am adding additional information
The value cannot be created locally in the method. It has to come from the class or some other method accessed by the class.
My Solution Based on the Answers:
Based on the answer by #EricJ. and #Jodrell. I went with option 1 and also created it as a private static method. I also found some details here to support this.
When creating a local variable to store the value will the "final" keyword provide any advantages, if the variable will not be changed
In Java, final provides an optimization opportunity to the compiler. It states that the contents of the variable will not be changed. The keyword readonly provides a similar role in C#.
Whether or not that additional opportunity for optimization is meaningful depends on the specific problem. In many cases, the cost of other portions of the algorithm will be vastly larger than optimizations that the compiler is able to make due to final or readonly.
Use of those keywords has another benefit. They create a contract that the value will not change, which helps future maintainers of the code understand that they should not change the value (indeed, the compiler will not let them).
What is the best/right way of using Instance Variable within a private method (static and non-static)?
Pass as method argument
The value is already stored in the instance. Why pass it? Best case is this is not better than using the instance property/field. Worst case the JITer not inline the call, and will create a larger stack frame costing a few CPU cycles. Note: if you are calling a static method, then you must pass the variable as the static method cannot access the object instance.
Store locally by using the method to get the value - this.getClaimPropertyVertices();
This is what I do in general. Getters/setters are there to provide a meaningful wrapper around fields. In some cases, the getter will initialize the backing field (common pattern in C# when using serializers that do not call the object constructor. Don't get me started on that topic...).
Store locally by getting the value - this.claimPropertyVertices;
No, see above.
Use the instance variable directly in the method
Exactly the same as above. Using this or not using this should generate the exact same code.
UPDATE (based on your edit)
If the value is external to the object instance, and should not meaningfully be stored along with the instance, pass it in as a value to the method call.
If you write your functions with the static keyword whenever you can, there are several obvious benefits.
Its obvious what inputs effect the function from the signature.
You know that the function will have no side effects (unless you are passing by reference). This overlooks non-functional side effects, like changes to the GUI.
The function is not programtically tied to the class, if you decide that logically its behaviour has a better association with another entity, you can just move it. Then adjust any namespace references.
These benefits make the function easy to understand and simpler to reuse. They will also make it simpler to use the function in a Multi Threaded context, you don't have to worry about contention on ever spreading side effects.
I will cavet this answer. You should write potentially resuable functions with the static keyword. Simple or obviously non-resulable functionality should just access the private member or getter, if implemented.
Pretty straight forward. MSDN states that you can use ref, but not out for partial methods. I'm just curious as to the why? It was my understanding that when code is compiled, the partials are merged, so what is up with the restriction? Is there more to partial than just making code files cleaner and organized (i.e. eyecandy)?
Reference: MSDN Article - "Partial methods can have ref but not out parameters."
You got to consider what happens if the partial method isn't implemented.
What happens then is that all calls to the method is just stripped out as though they never happened.
So for a method using out, it would look like this:
stream s;
GetStream(out s);
s.Write(...);
and be compiled as though it said this:
stream s;
s.Write(...);
This code is not allowed because s has not been initialized. The guarantee that the variable would be initialized by the time you try to call the Write method on it was tied up with the call to GetStream.
It is the same with methods returning data. Since the entire method call is just not compiled if you haven't implemented the partial method, you need to consider what you can and cannot do and still leave the code that calls it valid. In terms of out and return values, it has the potential of leaving the calling code invalid or incomplete, so it is not allowed.
As for ref, that is valid since the initialization has been taken care of by the calling code:
stream s = null;
GetStream(ref s); // may be stripped out
if (s != null)
s.Write(...);
Because unlike ref parameters, out parameters MUST be initialized before the method returns. If the partial method is not implemented (which is a valid scenario,) how can it be initialized?
My guess would be because out parameters don't need to be initialized whereas ref parameters do.
If you used an out parameter on a partial method, how could C# verify that the parameter was initialized or not?
An out parameter suggests that you want a value out of the method. If the method doesn't exist, it can't provide that value.
The alternative would be to set the variable's value explicitly to its default value (0, null etc) instead of executing the method call. That way the variable would still be definitely initialized - although the default value may not be a terribly useful one. I believe the C# team have considered this - it may even make it into a future version, who knows? Personally I doubt that it would be particularly useful, but the possibility is there.
For the moment, you could always use a ref parameter instead, and just initialize the variable manually before the call to whatever the default value should be.
I would assume the reason is because a partial method with only a signature (i.e. no implementation) is still valid. If you had an out parameter an implementation-less method would always cause an error (as there's nothing assigning the out value)
A partial method is split across partial classes. A method is required to assign a value to an OUT parameter. Partial methods may or may not be implemented. It would mean multiple code chunks is trying to assign value to the OUT parameter.
As everyone else has stated out params must be assigned. To add this will generate compiler error CS0177 ref on the other hand must be assigned prior to making the call.