Search Results

Search found 958 results on 39 pages for 'dispose'.

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

  • The Dispose Pattern (and FxCop warnings)

    - by Scott Dorman
    [This is actually a response to Bill’s blog post, but since it isn’t possible to leave this as a comment on his blog it’s a post here.] There are many different ways to implement the Dispose pattern correctly. Some are (in my opinion) better than others. In Bill’s blog post he presents a particular pattern, which is an excerpt from his book (Effective C#). The issue centers around the fact that a reader took the code sample presented in the book and ran FxCop (Code Analysis) on it, which generated a warning: “Ensure that base.Dispose() is always called.” The “lesson learned” that Bill presents is that “tools are there to help us, not control us.” While I completely agree with the belief that tools are there to help us, I think it’s important to understand why FxCop is raising this particular warning. The code presented in Bill’s book looks like: // Have its own disposed flag.private bool disposed = false;protected override void Dispose(bool isDisposing){ // Don't dispose more than once. if (disposed) return; if (isDisposing) { // TODO: free managed resources here. } // TODO: free unmanaged resources here. // Let the base class free its resources. // Base class is responsible for calling // GC.SuppressFinalize( ) base.Dispose(isDisposing); // Set derived class disposed flag: disposed = true;} This code does follow all of the guidelines for implementing the Dispose pattern. In this case, it’s presumably part of a larger example showing how to implement the pattern as part of a base class. The reason FxCop is warning you about this code is the first if statement in the Dispose method, which will cause the method to exit if disposed is true. The problem here is that there is the possibility that if the disposed flag is true, the call to base.Dispose() will never be executed. As Bill points out, it is possible for some other code elsewhere in the class to set this flag. He states that this is an “unlikely occurrence.” While that is probably true, it can be a potentially dangerous assumption to make and is one that can be easily corrected. By changing the code slightly you can remove this assumption and correct the FxCop violation. private bool disposed = false;protected override void Dispose(bool disposing){ if (!disposed) { if (disposing) { // Dispose managed resources. } // Dispose unmanaged resources. disposed = true; } base.Dispose(disposing);} Using this implementation allows the call to base.Dispose() to always occur, which ensures that the the disposal chain is always properly followed. Technorati Tags: .NET,C#,Dispose Pattern

    Read the article

  • Recursion in Unity and Dispose pattern implementation

    - by Budda
    My class is inherited from UnityContainer (from Unity 2.0), here is source code: public class UnityManager : UnityContainer { private UnityManager() { _context = new MyDataClassesDataContext(); // ... } protected override void Dispose(bool disposing) { if ( disposing ) { _context.Dispose(); } base.Dispose(disposing); } private readonly CMCoreDataClassesDataContext _context; } When Dispose method is called for the instance of UnityManager class it drop into recursion... Why? As far as I know base.Dispose should call the Dispose method of base class only... isn't it? Who call back the Dispose(bool) of UnityManager? How to prevent that? Thanks.

    Read the article

  • Using Dispose on a Singleton to Cleanup Resources

    - by ImperialLion
    The question I have might be more to do with semantics than with the actual use of IDisposable. I am working on implementing a singleton class that is in charge of managing a database instance that is created during the execution of the application. When the application closes this database should be deleted. Right now I have this delete being handled by a Cleanup() method of the singleton that the application calls when it is closing. As I was writing the documentation for Cleanup() it struck me that I was describing what a Dispose() method should be used for i.e. cleaning up resources. I had originally not implemented IDisposable because it seemed out of place in my singleton, because I didn't want anything to dispose the singleton itself. There isn't currently, but in the future might be a reason that this Cleanup() might be called but the singleton should will need to still exist. I think I can include GC.SuppressFinalize(this); in the Dispose method to make this feasible. My question therefore is multi-parted: 1) Is implementing IDisposable on a singleton fundamentally a bad idea? 2) Am I just mixing semantics here by having a Cleanup() instead of a Dispose() and since I'm disposing resources I really should use a dispose? 3) Will implementing 'Dispose()' with GC.SuppressFinalize(this); make it so my singleton is not actually destroyed in the case I want it to live after a call to clean-up the database.

    Read the article

  • How do I manually Dispose RSACryptoServiceProvider?

    - by phq
    I have read on MSDN(see Important note) that RSACryptoServiceProvider must be disposed. They give the example: using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) Now I'm trying to include RSACryptoServiceProvider into MyClass making use of it in several Methods. With this setup I cannot use the using statement. Instead I try to call the .Dispose() Method of the RSACryptoServiceProvider object at a suitable time but then I get the compile error message: `System.Security.Cryptography.AsymmetricAlgorithm.Dispose(bool)' is inaccessible due to its protection level Is RSACryptoServiceProvider not supposed to be used longer than one function call(using the using statement)? How can I fix this, is not making the Dispose call an option?

    Read the article

  • Object not disposed after calling the Dispose() function.

    - by Pavan Navali
    Hi, I have query regarding the disposing of an object. The scenario is as follows. In a Desktop Appication, developed in C#, I have a function in which a object in created like this. namespace Class 1 { variables section; .... .... Function1() { local variables; try { Object1 obj = new Object1(); .... .... if(true) { .... } else { **obj.Dispose();** } } catch() {} finally {} } } The object is not disposed when the else part is executed. The msdn link for this is http://msdn.microsoft.com/en-us/library/system.componentmodel.component.dispose(VS.90).aspx according to which the component should realase all the resources used by it. I would like to know, why the object is not disposed. Thank you. Pavan Navali.

    Read the article

  • Right way to dispose Image/Bitmap and PictureBox

    - by kornelijepetak
    I am trying to develop a Windows Mobile 6 (in WF/C#) application. There is only one form and on the form there is only a PictureBox object. On it I draw all desired controls or whatever I want. There are two things I am doing. Drawing custom shapes and loading bitmaps from .png files. The next line locks the file when loading (which is an undesired scenario): Bitmap bmp = new Bitmap("file.png"); So I am using another way to load bitmap. public static Bitmap LoadBitmap(string path) { using (Bitmap original = new Bitmap(path)) { return new Bitmap(original); } } This is I guess much slower, but I don't know any better way to load an image, while quickly releasing the file lock. Now, when drawing an image there is method that I use: public void Draw() { Bitmap bmp = new Bitmap(240,320); Graphics g = Graphics.FromImage(bmp); // draw something with Graphics here. g.Clear(Color.Black); g.DrawImage(Images.CloseIcon, 16, 48); g.DrawImage(Images.RefreshIcon, 46, 48); g.FillRectangle(new SolidBrush(Color.Black), 0, 100, 240, 103); pictureBox.Image = bmp; } This however seems to be some kind of a memory leak. And if I keep doing it for too long, the application eventually crashes. Therefor, I have X questions: 1.) What is the better way for loading bitmaps from files without locking the file? 2.) What objects needs to be manually disposed in the Draw() function (and in which order) so there's no memory leak and no ObjectDisposedException throwing? 3.) If pictureBox.Image is set to bmp, like in the last line of the code, would pictureBox.Image.Dispose() dispose only resources related to maintaining the pictureBox.Image or the underlying Bitmap set to it?

    Read the article

  • Call Dispose() on a WindowsIdentity object? C#

    - by Andy
    I am retrieving a WindowsIdentity object by calling: win_id = System.Security.Principal.WindowsIdentity.GetCurrent(); with the intention of getting the currently logged on user name, which works fine. WindowsIdentity implements IDisposable, but since I din't create the object myself, do I still need to call .Dispose() on it when I am finished with it or not? Thanks.

    Read the article

  • Dispose Form opened in MainForm tab

    - by fireBand
    Hi, I have a MainForm which has tab Control and several independent form. I open each Individual From in the tab of the main form. A "Close Tab" button on the MainFrom closes the current tab, its implementation is below. This closes the current tab but what I also need is to dispose the From whose tab is closed but I am not sure how to get the instance of the form.' Any help is appreciated Thanks in Advance. 'Close the current tab Private Sub CloseCurrentTab() 'Close the current tab Dim tabPageSave As TabPage tabPageSave = tcDisplayDetails.SelectedTab tcDisplayDetails.TabPages.Remove(tabPageSave) End Sub

    Read the article

  • Do I need to Dispose to deregister events?

    - by Sean
    Say I have two classes, and neither of them are GUI components. Class A is a short lived object that registers for an event declared by a long lived object B. For example public A(B b) { b.ChangeEvent += OnChangeEvent; } If A never deregisters from B's event, will A never be garbage collected? Does A need a Dispose method just to deregister from B's event? There is also a related second question. If A and B should both live for the entire execution time of the application, does A need to deregister?

    Read the article

  • Java CountDownLatch used to wait for JFrame to dispose

    - by Brian
    I have referenced this previous question as well as other sources, but cannot get CountDownLatch to work correctly. Background: mainFrame creates new Frame called dataEntryFrame. When dataEntryFrame "Submit" button is clicked, record added to database and dataEntryFrame disposed. At this point, mainFrame should clear and reload a jList that shows all records. Issue: When dataEntryFrame loads, java freezes, dataEntryFrame components never load. I cannot get past this part... then, in the DataEntryFrame, CountDownLatch should only decrements after the submit button is clicked, successfully adds a record to a database table, and disposes itself. Or when the user clicks cancel... Code: From MainFrame CountDownLatch dataEntryDone = new CountDownLatch(1); DataEntryFrame f = new DataEntryFrame(dataEntryDone); Thread newThread = new Thread(f); newThread.start(); dataEntryDone.await(); Code: From DataEntryFrame public void run(){ initComponents(); loadOtherData(); this.setVisible(true); } void submit(){ addRecord(); this.dispose() dataEntryDone.countDown(); }

    Read the article

  • How to dispose a Writeable Bitmap? (WPF)

    - by Mario
    Some time ago i posted a question related to a WriteableBitmap memory leak, and though I received wonderful tips related to the problem, I still think there is a serious bug / (mistake made by me) / (Confusion) / (some other thing) here. So, here is my problem again: Suppose we have a WPF application with an Image and a button. The image's source is a really big bitmap (3600 * 4800 px), when it's shown at runtime the applicaton consumes ~90 MB. Now suppose i wish to instantiate a WriteableBitmap from the source of the image (the really big Image), when this happens the applications consumes ~220 MB. Now comes the tricky part, when the modifications to the image (through the WriteableBitmap) end, and all the references to the WriteableBitmap (at least those that I'm aware of) are destroyed (at the end of a method or by setting them to null) the memory used by the writeableBitmap should be freed and the application consumption should return to ~90 MB. The problem is that sometimes it returns, sometimes it does not. Here is a sample code: // The Image's source whas set previous to this event private void buttonTest_Click(object sender, RoutedEventArgs e) { if (image.Source != null) { WriteableBitmap bitmap = new WriteableBitmap((BitmapSource)image.Source); bitmap.Lock(); bitmap.Unlock(); //image.Source = null; bitmap = null; } } As you can see the reference is local and the memory should be released at the end of the method (Or when the Garbage collector decides to do so). However, the app could consume ~224 MB until the end of the universe. Any help would be great.

    Read the article

  • Any sense to set obj = null(Nothing) in Dispose()?

    - by serhio
    Is there any sense to set custom object to null(Nothing in VB.NET) in the Dispose() method? Could this prevent memory leaks or it's useless?! Let's consider two examples: public class Foo : IDisposable { private Bar bar; // standard custom .NET object public Foo(Bar bar) { this.bar = bar; } public void Dispose() { bar = null; // any sense? } } public class Foo : RichTextBox { // this could be also: GDI+, TCP socket, SQl Connection, other "heavy" object private Bitmap backImage; public Foo(Bitmap backImage) { this.backImage = backImage; } protected override void Dispose(bool disposing) { if (disposing) { backImage = null; // any sense? } } }

    Read the article

  • WPF MVVM UserControl Binding "Container", dispose to avoid memory leak.

    - by user178657
    For simplicity. I have a window, with a bindable usercontrol <UserControl Content="{Binding Path = BindingControl, UpdateSourceTrigger=PropertyChanged}"> I have two user controls, ControlA, and ControlB, Both UserControls have their own Datacontext ViewModel, ControlAViewModel and ControlBViewModel. Both ControlAViewModel and ControlBViewModel inh. from a "ViewModelBase" public abstract class ViewModelBase : DependencyObject, INotifyPropertyChanged, IDisposable........ Main window was added to IoC... To set the property of the Bindable UC, i do ComponentRepository.Resolve<MainViewWindow>().Bindingcontrol= new ControlA; ControlA, in its Datacontext, creates a DispatcherTimer, to do "somestuff".. Later on., I need to navigate elsewhere, so the other usercontrol is loaded into the container ComponentRepository.Resolve<MainViewWindow>().Bindingcontrol= new ControlB If i put a break point in the "someStuff" that was in ControlA's datacontext. The DispatcherTimer is still running... i.e. loading a new usercontrol into the bindable Usercontrol on mainwindow does not dispose/close/GC the DispatcherTimer that was created in the DataContext View Model... Ive looked around, and as stated by others, dispose doesnt get called because its not supposed to... :) Not all my usercontrols have DispatcherTimer, just a few that need to do some sort of "read and refresh" updates./. Should i track these DispatcherTimer objects in the ViewModelBase that all Usercontrols inh. and manually stop/dispose them everytime a new usercontrol is loaded? Is there a better way?

    Read the article

  • How to correctly Dispose a SourceVoice once its finished

    - by clamp
    i am starting to play a sound with XAudio2 and SourceVoice and once its finished, it should be correctly disposed to not have any leaks. i was expecting it to be something like this: sourceVoice.Start(); sourceVoice.StreamEnd += delegate { if (!sourceVoice.IsDisposed) { sourceVoice.DestroyVoice(); sourceVoice.Dispose(); } }; but that crashes with a read access violation in native code deep in XAudio2.dll which i cant debug.

    Read the article

  • C# Finalize/Dispose pattern

    - by robUK
    Hello, C# 2008 I have been working on this for a while now. And I am still confused about some issues. My questions below 1) I know that you only need a finalizer if you are disposing of unmanaged resources. However, if you are using managed resources that make calls to unmanaged resources. Would you still need to implement a finalizer? 2) However, if you develop a class that doesn't use any unmanged resources directly or indirectly and you implement the IDisposable so that clients of your class can use the 'using statement'. Would it be acceptable to implement the IDisposable just so that clients of your class can use the using statement? using(myClass objClass = new myClass()) { // Do stuff here } 3) I have developed this simple code below to demostrate the Finalize/dispose pattern: public class NoGateway : IDisposable { private WebClient wc = null; public NoGateway() { wc = new WebClient(); wc.DownloadStringCompleted += wc_DownloadStringCompleted; } // Start the Async call to find if NoGateway is true or false public void NoGatewayStatus() { // Start the Async's download // Do other work here wc.DownloadStringAsync(new Uri(www.xxxx.xxx)); } private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { // Do work here } // Dispose of the NoGateway object public void Dispose() { wc.DownloadStringCompleted -= wc_DownloadStringCompleted; wc.Dispose(); GC.SuppressFinalize(this); } } Question about the source code: 1) Here I have not added the finalizer. And normally the finalizer will be called by the GC, and the finalizer will call the Dispose. As I don't have the finalizer, when do I call the Dispose method? Is it the client of the class that has to call it? So my class in the example is called NoGateway and the client could use and dispose of the class like this: Would the Dispose method be automatically called when execution reaches the end of the using block? using(NoGateway objNoGateway = new NoGateway()) { // Do stuff here } Or does the client have to manually call the dispose method i.e.? NoGateway objNoGateway = new NoGateway(); // Do stuff with object objNoGateway.Dispose(); // finished with it Many thanks for helping with all these questions, 2) I am using the webclient class in my 'NoGateway' class. Because the webclient implements the IDisposable interface. Does this mean that the webclient indirectly uses unmanaged resources? Is there any hard and fast rule to follow about this. How do I know that a class uses unmanaged resources?

    Read the article

  • 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

  • C# how to correctly dispose of an SmtpClient?

    - by JL
    VS 2010 code analysis reports the following: Warning 4 CA2000 : Microsoft.Reliability : In method 'Mailer.SendMessage()', object 'client' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'client' before all references to it are out of scope. My code is : public void SendMessage() { SmtpClient client = new SmtpClient(); client.Send(Message); client.Dispose(); DisposeAttachments(); } How should I correctly dispose of client? Update: to answer Jons question, here is the dispose attachments functionality: private void DisposeAttachments() { foreach (Attachment attachment in Message.Attachments) { attachment.Dispose(); } Message.Attachments.Dispose(); Message = null; }

    Read the article

  • How can I dispose of an object (say a Bitmap) when it becomes orphaned ?

    - by Jelly Amma
    I have a class A providing Bitmaps to other classes B, C, etc. Now class A holds its bitmaps in a ring queue so after a while it will lose reference to the bitmap. While it's still in the queue, the same Bitmap can be checked out by several classes so that, say, B and C can both hold a reference to this same Bitmap. But it can also happen that only one of them checked out the Bitmap or even none of them. I would like to dispose of the bitmap when it's not being needed any more by either A, B or C. I suppose I have to make B and C responsible for somehow signaling when they're finished using it but I'm not sure about the overall logic. Should it be a call to something like DisposeIfNowOrphan() that would be called : 1 - when the Bitmap gets kicked out of the queue in class A 2 - when B is finished with it 3 - when C is finished with it If that's the best strategy, how can I evaluate the orphan state ? Any advice would be most welcome.

    Read the article

  • libgdx game not disposing

    - by Yesh
    My game does not exit entirely even after calling dispose() method. It loads a black screen when I launch it for the second time and works well if I kill the game manually and restart it. I get an error that says buffer not allocated with newUnsafeByteBuffer or already disposed when I try to dispose off the SpriteBatch object. This is were I suspect the problem to be. But not able to fix it entirely. Please help! Here is how I have built it (I have put the sample code here just to show you guys that there are no visible loop backs in dispose function, please correct me if I'm wrong)- In game screen, public void dispose() { AssetLoader.dispose(); render.dispose(); Gdx.app.exit(); } Under class AssetLoader- public void dispose(){ Texture.dispose(); sound.dispose(); } Under game render class - public void dispose(){ spritebatch.dispose(); //throws an error when I GameScreen.dispose is called font.dispose(); shaperender.dispose(); } I believe that my spritebatch isn't disposing which is causing the black screen but I cannot find a way to dispose it off successfully. Any help would be greatly appreciated.

    Read the article

  • Call HttpWebRequest in another thread as UI with Task class - avoid to dispose object created in Task scope

    - by John
    I would like call HttpWebRequest on another thread as UI, because I must make 200 request or server and downloaded image. My scenation is that I make a request on server, create image and return image. This I make in another thread. I use Task class, but it call automaticaly Dispose method on all object created in task scope. So I return null object from this method. public BitmapImage CreateAvatar(Uri imageUri, int sex) { if (imageUri == null) return CreateDefaultAvatar(sex); BitmapImage image = null; new Task(() => { var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { Byte[] buffer = new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); image = new BitmapImage { CreateOptions = BitmapCreateOptions.None, CacheOption = BitmapCacheOption.OnLoad }; image.BeginInit(); image.StreamSource = new MemoryStream(buffer); image.EndInit(); image.Freeze(); } }).Start(); return image; } How avoid it? Thank Mr. Jon Skeet try this: private Stream GetImageStream(Uri imageUri) { Byte[] buffer = null; //new Task(() => //{ var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { buffer= new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); } //}).Start(); return new MemoryStream(buffer); } It return object which is null a than try this: private Stream GetImageStream(Uri imageUri) { Byte[] buffer = null; new Task(() => { var request = WebRequest.Create(imageUri); var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { buffer= new Byte[response.ContentLength]; int offset = 0, actuallyRead = 0; do { actuallyRead = stream.Read(buffer, offset, buffer.Length - offset); offset += actuallyRead; } while (actuallyRead > 0); } }).Start(); return new MemoryStream(buffer); } Method above return null

    Read the article

  • Should I dispose GDI+ object before its creation?

    - by serhio
    Should I dispose GDI+ object before its creation? Is recommended to always Dispose GDI+ object after using it. by e.g. Pen p = new Pen(Color.Green); // use 'p' p.Dispose(); now, if I have this situation: Pen p = new Pen(Color.Green); // use green 'p' p = new Pen(Color.Red); // Should I Dispose my 'p' first? // use red 'p' p.Dispose();

    Read the article

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