What does this refer to inside of a using block in C#?
this inside of a using block refers to the same thing as this outside of a using block: the current instance of the class.
A using block should be used with all classes that implement the IDisposable interface. It's an implementation detail of the class if it wraps managed and/or unmanaged resources.
1 - this always refers to the object scope you are currently in for example
void myFunc(int sameName)
{
this.sameName += sameName;
}
in this case this.sameName refers to the classes variable called sameName while the one without the this qualifier refers to the local variables (use in case you have local/globals with the same name or for clarity).
2 - Unmanaged resources are sockets, httpservers, connections, filebuffers, etc.... Anything that is IDisposable (that isn't automatically GC'ed like persistent connections or some GUI elements like Modeless forms etc...)
3 - technically yes, if you don't explicity call File.Close() or place it within a using statement then the changes you made to the file may not get flushed back to disc so if you have a file buffer open you should always call Close() on it.
EDIT: You can ignore 2 and 3 since he removed them from the question but I'll leave them here just in case
Related
I am wonder what is best to do.
I have main function with iteration loop.
For each item in the list I need to get data from the db by using NHibernate.
There are sub functions which are called in the iteration loop body.
In each sub function I need to use data from the item association tables.
for ex. If the Item is Teacher, each func need the Teacher.Students and etc. In my case the record list include many items.
So my question what is better:
1 - To send the Teacher.Students to each sub func.
or 2 - Declare a class variable that all the func know it and it will initialized on each iteration.
Thank in advance!
Imagine you would maintain the code, but somebody else wrote it. It would be much easier for you to understand what a function does if you see what it is receiving as input. So you know what kind of data a function processes. You should not use a class variable if you can just call your function with this data as input.
You can read about good programming style at Elements of Programming Style
From there you get:
Use variables at the smallest possible level of scope. One implication of this rule is that you should minimize the use of global variables. There is a place in good programming style for global variables, and that is for a body of knowledge that will be acted on by many sections of the program, and which is in some sense the major essence of that program. Don't use global variables as a convenient means to communicate between two subroutines.
You should avoid using any kind of global variables and always store your data in the smallest possible scope. This is one of the principles of good design.
The code is so clearer easier to understand, maintain, reuse and change. Dependencies are kept low.
Imagine you need to change this code in the future. If you touch a global variable, you might possibly break some code on the other side (as other methods can use the same variable). If it is localizes, you just need to analyse the impact inside of the method.
Besides, the method with parameters is nicelly encapsulated and its signature is self-explanatory. YOu can even possibly reuse it in the future!
UPDATE
There are a lots of resources on internet, here is a good start: http://www.oodesign.com/design-principles.html
In your case the use of global variables clearly breaks the Open-closed Principle:
Software entities like classes, modules and functions should be open
for extension but closed for modifications.
If you use the global variable instead of sending parameter (Teacher.Students), your method is obviously not closed for modifications, as any change to this global variable (not part of the method!) cause potential crash in the method. With the parameter, your method is closed and protected.
I too think on the line of using functions instead class level variables.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling null on a class vs Dispose()
Just want some information regarding Disposing an Object.
I have create a Employee Class which i inherit from IDISPOSIBLE Interface. Below is the sample Code
public class Employee : IDisposable
{
private Int32 _RunID;
public Int32 RunID { get { return _RunID; } set { _RunID = value; } }
public void Dispose()
{
//Dispose(true);
}
}
Now my Question is, it a Good Coding Practice to Dispose every class we create and implementing/Inheriting it with IDisposible Interface even i have seen many other people code they directly set ObjEmployee = null; so just got confused which is good setting NULL or Implementing it With IDisposible Interface or None Of the Above ?
It depends, do you have managed resources (File handles, sockets, connections, etc....) that need to be gotten rid of along with your object? If yes then you need a Dispose() if your class contains basic types or just information you do not need to dispose and setting to null will give a hint to the GC to clear that memory.
When you set ObjEmployee = null, you only mark the object instance to be ready for the Garbage Collector, but you have no influence over when the actual clean-up would take place, and it may take a while. When you use the Dispose() method, the GC runs immediately and frees the memory the object was using.
The fundamental question, in deciding whether a class should implement IDisposable, is whether instances of that class have taken on the responsibility of seeing that other entities get cleaned up; typically those other entities will be altering their behavior on behalf of the IDisposable object and at the expense of other entities, and the IDisposable object is responsible for letting them know when they no longer need to do so.
For example, if any code, anywhere, uses the C function fopen() to open for read-write access a file which is located on a server, the server will alter its behavior by forbidding anyone else from accessing the file until it receives word that the program that opened it has no more need of it. When the program no longer needs exclusive use of the file, it can call fclose() which will in turn cause the server to be notified that the file should again be available to other applications.
If a method in a C# class calls a routine which calls fopen(), and that routine returns after putting the FILE* in a place the C# program knows about but nothing else does, that method takes on a responsibility for seeing that fclose() must somehow get called with that FILE*. The file needs to be fclosed(), and nothing else in the system has the information or impetus necessary to do so, so the responsiblity falls to that C# class.
If the C# method were to return without storing the FILE* anywhere, the file would never get closed, and nobody else, anywhere in the universe, would be able to use it unless or until the application exits. If the C# method has to exit without yielding exclusive use of the file, it must store the FILE* in a way that will ensure that someone, somewhere, will clean it up after exclusive use is no longer required. The normal pattern would be for the method to store the FILE* in a class field, and for class containing the method to implement IDisposable by copying and blanking that field, seeing if it was non-blank, and if it was non-blank, calling fclose() the stored FILE*.
The important thing to realize is that when an object is destroyed by the garbage collector, the system won't care what's in any of the object fields. It won't even look at them. What matters is whether the object has any unfulfilled responsibilities for ensuring that outside entities, which may not even be on the same machine, are informed when their services are no longer needed.
We're dealing with the GC being too quick in a .Net program.
Because we use a class with native resources and we do not call GC.KeepAlive(), the GC collects the object before the Native access ends. As a result the program crashes.
We have exactly the problem as described here:
Does the .NET garbage collector perform predictive analysis of code?
Like so:
{ var img = new ImageWithNativePtr();
IntPtr p = img.GetData();
// DANGER!
ProcessData(p);
}
The point is: The JIT generates information that shows the GC that img is not used at the point when GetData() runs. If a GC-Thread comes at the right time, it collects img and the program crashes. One can solve this by appending GC.KeepAlive(img);
Unfortunately there is already too much code written (at too many places) to rectify the issue easily.
Therefore: Is there for example an Attribute (i.e. for ImageWithNativePtr) to make the JIT behave like in a Debug build? In a Debug build, the variable img will remain valid until the end of the scope ( } ), while in Release it looses validity at the comment DANGER.
To the best of my knowledge there is no way to control jitter's behavior based on what types a method references. You might be able to attribute the method itself, but that won't fill your order. This being so, you should bite the bullet and rewrite the code. GC.KeepAlive is one option. Another is to make GetData return a safe handle which will contain a reference to the object, and have ProcessData accept the handle instead of IntPtr — that's good practice anyway. GC will then keep the safe handle around until the method returns. If most of your code has var instead of IntPtr as in your code fragment, you might even get away without modifying each method.
You have a few options.
(Requires work, more correct) - Implement IDisposable on your ImageWithNativePtr class as it compiles down to try { ... } finally { object.Dispose() }, which will keep the object alive provided you update your code with usings. You can ease the pain of doing this by installing something like CodeRush (even the free Xpress supports this) - which supports creating using blocks.
(Easier, not correct, more complicated build) - Use Post Sharp or Mono.Cecil and create your own attribute. Typically this attribute would cause GC.KeepAlive() to be inserted into these methods.
The CLR has nothing built in for this functionality.
I believe you can emulate what you want with a container that implements IDispose, and a using statement. The using statement allows for defining the scope and you can place anything you want in it that needs to be alive over that scope. This can be a helpful mechanism if you have no control over the implementation of ImageWithNativePtr.
The container of things to dispose is a useful idiom. Particularly when you really should be disposing of something ... which is probably the case with an image.
using(var keepAliveContainer = new KeepAliveContainer())
{
var img = new ImageWithNativePtr();
keepAliveContainer.Add(img);
IntPtr p = img.GetData();
ProcessData(p);
// anything added to the container is still referenced here.
}
Rookie question about when a data reader actually gets released when it’s constructed in a class using ref vs. var. I’ve been testing this today and the results are puzzling me a bit – hoping to get this clear in my head.
I have a class that I use for fetching data via ODBC from numerous remote servers but I need to restrict how many ODBC connections are open to each server I'm attached to – so I’m being careful about properly disposing data readers when I’m done with them before opening another. Short version is I have a method called FillDataReader that takes a data reader object, and fills it based on your query and passes it back.
If I pass it using ref and dispose the data reader from the calling side, all is well. The connection is released immediately and the client side can get another data reader filled without burning a connection. However if I pass by value, the resource is not released and if I open another data reader from the client side I now have two connections to that server.
Conceptually I get the difference – with ref only a single address is being used as it’s passing a “pointer to a pointer” and the dispose releases that resource. OK, but even if passing by value and doing an explicit dispose on the client side what, exactly, is holding the resource? I’d rather pass by value here so I can use the nifty using construct on the client side but more importantly I want to understand better what’s happening here. In a nutshell here’s what it looks like
[DB fetch class]
public bool FillDataReader(string pQueryString, ref System.Data.Odbc.OdbcDataReader pDataReader, out string pErrorReason)
{
(uses a connection object that’s been established at class construction time and stays up all the time)
...
try
{
pDataReader = _Command.ExecuteReader();
}
...
}
[Calling class]
strSQL = "SELECT Alias, ObjectID, FROM vw_GlobalUser";
if (ServerList[currentServer].DatabaseFunctions.FillDataReader(strSQL, ref drTemp, false, out strErrorReason) == false)
….
drTemp.Dispose();
(at this point the connection is released to the server)
However if I take the ref out at the point of Dispose in the calling class the connection is not released. It goes away eventually but I need it gone immediately (hence the call to dispose).
So is the fill function in the DB fetch class hanging onto a reference to the allocated space on the heap somehow? I’m not sure I understand why that is – understood it’s using another copy of the address to the data reader on the stack to reference the data reader object on the heap there but when it goes out of scope, isn’t that released? Maybe I need more coffee…
Since your calling code needs to receive the reference to release the object, you do need a ref (or out). Otherwise the parameter is only passed to the method, but not back, so that the drTemp isn't updated with the data reader created in the FillDataReader method.
Note that you may want to change the signature as follows to make the intention more clear:
public Result TryGetDataReader(string pQueryString, out System.Data.Odbc.OdbcDataReader pDataReader)
Changes that I propose:
Introduced the naming convention with "Try", which is common for this type of method
Made the pDataReader an out, since it doesn't need to be initialized when calling the method
Introduced a "Result" type, which should carry the success information and the error message (if any)
Refactoring some code again. Seeing some of this in one of the ASP.NET pages:
using (TextBox txtBox = e.Row.Cells[1].FindControl("txtBox") as TextBox)
{
}
There is no need to dispose txtBox, because it's just a reference to an existing control. And you don't want the control disposed at all. I'm not even sure this isn't harmful - like it would appear to ask for the underlying control to be disposed inappropriately (although I have not yet seen any ill effects from it being used this way).
TextBox inherits its implementation of IDisposable from its Component superclass. That implementation removes the component from its site container if it has one.
So, doing that might have nefarious effects if the text box actually resides in a site container. Also, after calling Dispose() on an object, you should not use it again, no matter what (it's not in a usable state anymore).
I'd suggest you avoid that pattern with ASP.NET web controls.
This is wrong, it shouldnt be used like this. I would imagine there are potential problems using this that wont show up immediately. The textboxes dispose is called upon leaving the using statement but it wont be garbage collected immediately. If it is collected then you will have problems later when you try to access that control.
The TextBox instance could potentially be null if not found, so Dispose() is called a NullReferenceException would be thrown.
I've never seen that pattern in practice, but if you need to use it, it'd be worth handling any potential errors.
There should be no negative secondary effects, but it's not necessary either. If we did using (x) { ... } on everything that implements IDisposable in the CLR most C# code would be unreadable.
Actually, here the TextBox instance is accessible only to the context inside the brackets of using statement, maybe that was the main reason of using it.
From MSDN:
Within the using block, the object
is read-only and cannot be modified
or reassigned.
So I guess you can only read the textbox properties, but not change them, inside the using block.