Search Results

Search found 257 results on 11 pages for 'idisposable'.

Page 2/11 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Is There a Time at which to ignore IDisposable.Dispose?

    - by Mystagogue
    Certainly we should call Dipose() on IDisposable objects as soon as we don't need them (which is often merely the scope of a "using" statement). If we don't take that precaution then bad things, from subtle to show-stopping, might happen. But what about "the last moment" before process termination? If your IDisposables have not been explicitly disposed by that point in time, isn't it true that it no longer matters? I ask because unmanaged resources, beneath the CLR, are represented by kernel objects - and the win32 process termination will free all unmanaged resources / kernel objects anyway. Said differently, no resources will remain "leaked" after the process terminates (regardless if Dispose() was called on lingering IDisposables). Can anyone think of a case where process termination would still leave a leaked resource, simply because Dispose() was not explicitly called on one or more IDisposables? Please do not misunderstand this question: I am not trying to justify ignoring IDisposables. The question is just technical-theoretical. EDIT: And what about mono running on Linux? Is process termination there just as "reliable" at cleaning up unmanaged "leaks?"

    Read the article

  • Method returns an IDisposable - Should I dispose of the result, even if it's not assigned to anythin

    - by mjd79
    This seems like a fairly straightforward question, but I couldn't find this particular use-case after some searching around. Suppose I have a simple method that, say, determines if a file is opened by some process. I can do this (not 100% correctly, but fairly well) with this: public bool IsOpen(string fileName) { try { File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None); } catch { // if an exception is thrown, the file must be opened by some other process return true; } } (obviously this isn't the best or even correct way to determine this - File.Open throws a number of different exceptions, all with different meanings, but it works for this example) Now the File.Open call returns a FileStream, and FileStream implements IDisposable. Normally we'd want to wrap the usage of any FileStream instantiations in a using block to make sure they're disposed of properly. But what happens in the case where we don't actually assign the return value to anything? Is it still necessary to dispose of the FileStream, like so: try { using (File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None)); { /* nop */ } } catch { return true; } Should I create a FileStream instance and dispose of that? try { using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None)); } ... Or are these totally unnecessary? Can we simply call File.Open and not assign it to anything (first code example), and let the GC dispose of it right away?

    Read the article

  • Disposable Registry: good pattern?

    - by illdev
    Imagine a: public class Global : IDisposable { private static readonly List<IDisposable> Disposables = new List<IDisposable>(); public void ApplicationStart() { var heavyLifter = new HeavyLifter(); Disposables.Add(heavyLifter); } public void Dispose() { Disposables.ForEach(d => d.Dispose()); } } I am somewhat inexperienced with IDisposable. Is this a viable pattern?

    Read the article

  • Is there a list of common object that implement IDisposable for the using statement?

    - by SkippyFire
    I was wondering if there was some sort of cheat sheet for which objects go well with the using statement... SQLConnection, MemoryStream, etc. Taking it one step further, it would be great to even show the other "pieces of the puzzle", like how you should actually call connection.Close() before the closing using statement bracket. Anything like that exist? If not, maybe we should make one.

    Read the article

  • Proper use of the IDisposable interface

    - by cwick
    I know from reading the MSDN documentation that the "primary" use of the IDisposable interface is to clean up unmanaged resources http://msdn.microsoft.com/en-us/library/system.idisposable.aspx. To me, "unmanaged" means things like database connections, sockets, window handles, etc. But, I've seen code where the Dispose method is implemented to free managed resources, which seems redundant to me, since the garbage collector should take care of that for you. For example: public class MyCollection : IDisposable { private List<String> _theList = new List<String>(); private Dictionary<String, Point> _theDict = new Dictionary<String, Point>(); // Die, you gravy sucking pig dog! public void Dispose() { _theList.clear(); _theDict.clear(); _theList = null; _theDict = null; } My question is, does this make the garbage collector free memory used by MyCollection any faster than it normally would? edit: So far people have posted some good examples of using IDisposable to clean up unmanaged resources such as database connections and bitmaps. But suppose that _theList in the above code contained a million strings, and you wanted to free that memory now, rather than waiting for the garbage collector. Would the above code accomplish that?

    Read the article

  • How do I know if I have an unmanaged resource?

    - by Shiftbit
    I've read that unmanaged resource are considered file handles, streams, anything low level. Does MSDN or any other source explain how to recognize an unmanaged resource? I can't seem to find any examples on the net that show unmanaged code, all the examples just have comments that say unmanaged code here. Can someone perhaps provide a realworld example where I would handle an unmanaged resources in an IDispose interface? I provided the IDisposable interface for your convience. How do I identify an unmanaged resource? Thanks in advance! IDisposable Reference Public Class Sample : Implements IDisposable Private disposedValue As Boolean = False 'To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(ByVal disposing As Boolean) If Not Me.disposedValue Then If disposing Then ' TODO: free other state (managed objects). End If ' TODO: free your own state (unmanaged objects). ' TODO: set large fields to null. End If Me.disposedValue = True End Sub ' This code added by Visual Basic to correctly implement the disposable pattern. Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub End Class

    Read the article

  • .NET: How do I know if I have an unmanaged resource?

    - by Shiftbit
    I've read that unmanaged resource are considered file handles, streams, anything low level. Does MSDN or any other source explain how to recognize an unmanaged resource? I can't seem to find any examples on the net that show unmanaged code, all the examples just have comments that say unmanaged code here. Can someone perhaps provide a realworld example where I would handle an unmanaged resources in an IDispose interface? I provided the IDisposable interface for your convience. How do I identify an unmanaged resource? Thanks in advance! IDisposable Reference Public Class Sample : Implements IDisposable Private disposedValue As Boolean = False 'To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(ByVal disposing As Boolean) If Not Me.disposedValue Then If disposing Then ' TODO: free other state (managed objects). End If ' TODO: free your own state (unmanaged objects). ' TODO: set large fields to null. End If Me.disposedValue = True End Sub ' This code added by Visual Basic to correctly implement the disposable pattern. Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub End Class

    Read the article

  • Should I implement IDisposable here?

    - by dotnetdev
    My method which calls SQL Server returns a datareader but because of what I need to do (return the datareader to the calling method which is in page code-behind), I can't close the connection in the class of the method which calls sql server, so I have no finally or using blocks. Is the correct way of disposing resources to make the class implement IDisposable? Or from the caller, explicitly dispose the unmanged resource (class-level fields)? Thanks

    Read the article

  • Delayed instantiation with c# using statment

    - by fearofawhackplanet
    Is there any way to write a using statement without instantiating the IDisposable immediately? For example, if I needed to do something like: using (MyThing thing) { if (_config == null) { thing = new MyThing(); } else { thing = new MyThing(_config); } // do some stuff } // end of 'using' Is there an accepted pattern for cases like this? Or am I back to handling the IDisposable explicitly again?

    Read the article

  • System::IDisposable woes

    - by shadeMe
    public ref class ScriptEditor : public Form { public: typedef map<UInt32, ScriptEditor^> AlMap; static AlMap AllocationMap; Form^ EditorForm; RichTextBox^ EditorBox; StatusBar^ EditorStatusBar; StatusBarPanel^ StatusBarLineNo; void Destroy() { EditorForm->Close(); } ScriptEditor(unsigned int PosX, unsigned int PosY); }; The above code throws an Error C2039: '{dtor}' : is not a member of 'System::IDisposable'. I'm quite lost after having looked into articles that explain how the CLR manages memory. Any advice on getting rid of it would be appreciated. My first dabble in C+++/CLI isn't going too well.

    Read the article

  • EntityFramework gives IDisposable error

    - by Snoop Dogg
    I use EF for the back-end DataLayer in my asp.net websites. I create a class library and add the Model in it, reference it and use it from the ASP.NET Website. But this time, I generated the model from database but it seems does not implement IDisposable, and the methods I used to see are not there. DeleteObject , SaveChanges etc. There are only Two tables in the DB and the Model was generated with only the TableSets and two methods AddToTableSet ... Had anybody encountered such a problem?

    Read the article

  • ASP.NET web services leak memory when (de)serializing disposable objects?

    - by Serilla
    In the following two cases, if Customer is disposable (implementing IDisposable), I believe it will not be disposed by ASP.NET, potentially being the cause of a memory leak: [WebMethod] public Customer FetchCustomer(int id) { return new Customer(id); } [WebMethod] public void SaveCustomer(Customer value) { // save it } This flaw applies to any IDisposable object. So returning a DataSet from a ASP.NET web service, for example, will also result in a memory leak - the DataSet will not be disposed. In my case, Customer opened a database connection which was cleaned up in Dispose - except Dispose was never called resulting in loads of unclosed database connections. I realise there a whole bunch of bad practices being followed here (its only an example anyway), but the point is that ASP.NET - the (de)serializer - is responsible for disposing these objects, so why doesn't it? This is an issue I was aware of for a while, but never got to the bottom of. I'm hoping somebody can confirm what I have found, and perhaps explain if there is a way of dealing with it.

    Read the article

  • Is it important to dispose SolidBrush and Pen?

    - by Joe
    I recently came across this VerticalLabel control on CodeProject. I notice that the OnPaint method creates but doesn't dispose Pen and SolidBrush objects. Does this matter, and if so how can I demonstrate whatever problems it can cause? EDIT This isn't a question about the IDisposable pattern in general. I understand that callers should normally call Dispose on any class that implements IDisposable. What I want to know is what problems (if any) can be expected when GDI+ object are not disposed as in the above example. It's clear that, in the linked example, OnPaint may be called many times before the garbage collector kicks in, so there's the potential to run out of handles. However I suspect that GDI+ internally reuses handles in some circumstances (for example if you use a pen of a specific color from the Pens class, it is cached and reused). What I'm trying to understand is whether code like that in the linked example will be able to get away with neglecting to call Dispose. And if not, to see a sample that demonstrated what problems it can cause. I should add that I have very often (including the OnPaint documentation on MSDN) seen WinForms code samples that fail to dispose GDI+ objects.

    Read the article

  • IUsable: controlling resources in a better way than IDisposable

    - by Ilya Ryzhenkov
    I wish we have "Usable" pattern in C#, when code block of using construct would be passed to a function as delegate: class Usable : IUsable { public void Use(Action action) // implements IUsable { // acquire resources action(); // release resources } } and in user code: using (new Usable()) { // this code block is converted to delegate and passed to Use method above } Pros: Controlled execution, exceptions The fact of using "Usable" is visible in call stack Cons: Cost of delegate Do you think it is feasible and useful, and if it doesn't have any problems from the language point of view? Are there any pitfalls you can see? EDIT: David Schmitt proposed the following using(new Usable(delegate() { // actions here }) {} It can work in the sample scenario like that, but usually you have resource already allocated and want it to look like this: using (Repository.GlobalResource) { // actions here } Where GlobalResource (yes, I know global resources are bad) implements IUsable. You can rewrite is as short as Repository.GlobalResource.Use(() => { // actions here }); But it looks a little bit weird (and more weird if you implement interface explicitly), and this is so often case in various flavours, that I thought it deserve to be new syntactic sugar in a language.

    Read the article

  • .NET CF 2.0: Stream implements IDisposable ... kind of?

    - by mvanbem
    I've run into something odd in a .NET CF 2.0 project for Pocket PC 2003 (Visual Studio 2005). I was dealing with a System.IO.Stream object and found that the IDE wouldn't auto-complete the Dispose() method. I typed it in manually and received: 'System.IO.Stream.Dispose(bool)' is inaccessible due to its protection level The error is referring to the protected Dispose(bool) method. Dispose() is either private or not present. Question 1: How is this possible? Stream implements IDisposable: public abstract class Stream : MarshalByRefObject, IDisposable ... and IDisposable requires a Dispose() method: public interface IDisposable { void Dispose(); } I know the compiler won't let me get away with that in my code. Question 2: Will I cause problems by working around and disposing my streams directly? IDisposable idisp = someStream; idisp.Dispose(); The implicit cast is accepted by the compiler.

    Read the article

  • Long overdue (for me) question about disposing managed objects in .Net, VB.Net, C#

    - by Jules
    I can't believe I'm still confused about this but, any way, lets finally nail it: I have a class that overrides OnPaint to do some drawing. To speed things up, I create the pens, brushes etc before hand, in the construtor, so that OnPaint does not need to keep creating and disposing them. Now, I make sure that I always dispose of such objects, but I have the feeling I don't need to because, despite the fact they implement IDisposable, they're managed objects. Is this correct?

    Read the article

  • C# On Quit WebPage Delete Files and Folders on Server with no user action

    - by user325558
    Hi, I have some problems to delete temporary folder and files on my server when users not finish some action in webpages and quit to other webpages. Initialy at Page Load folders are created to allow the user to load files.I have tried implementing destruction during Idisposable without success. Could someone point the best method to delete folders and files when user quit the page with no action or cancel button. Thanks.

    Read the article

  • return the variable used for using inside the using C#

    - by di3go
    Hello, I am returning the variable I am creating in a using statement inside the using statement (sounds funny): public DataTable foo () { using (DataTable properties = new DataTable()) { // do something return properties; } } Will this Dispose the properties variable?? After doing this am still getting this Warning: Warning 34 CA2000 : Microsoft.Reliability : In method 'test.test', call System.IDisposable.Dispose on object 'properties' before all references to it are out of scope. Any Ideas? Thanks

    Read the article

  • IEnumerator: Is it normal to have an empty Dispose method?

    - by C. Ross
    I'm writing an IEnumerator<T> class to iterate over a COM collection I'm wrappering. I've noticed that IEnumerator<T> extends IDisposable, so I'm required to implement the Dispose method. However, I can't think of anything I would put there, as I only have a reference to the collection (which I wouldn't want being disposed at the end of a foreach), and an int for the index. Is it normal to leave the Dispose method empty?

    Read the article

  • Combining foreach and using

    - by apoorv020
    I'm iterating over a ManageObjectCollection.( which is part of WMI interface). However the important thing is, the following line of code. : foreach (ManagementObject result in results) { //code here } The point is that ManageObject also implements IDisposable, so I would like to put "result" variable in a using block. Any idea on how to do this, without getting too weird or complex?

    Read the article

  • Help me understand Dispose() implementation code from MSDN

    - by Benny
    the following code is from MSDN: Idisposable pattern protected virtual void Dispose(bool disposing) { // If you need thread safety, use a lock around these // operations, as well as in your methods that use the resource. if (!_disposed) { if (disposing) { if (_resource != null) _resource.Dispose(); Console.WriteLine("Object disposed."); } // Indicate that the instance has been disposed. _resource = null; _disposed = true; } } why the following statement: _resource = null; _disposed = true; are not enclosed by if (disposing) statement block? for me i would probably write like this: if (disposing) { if (_resource != null) { _resource.Dispose(); _resource = null; _disposed = true; } Console.WriteLine("Object disposed."); } anything wrong with my version?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >