IClearCase, IClearTool usage in C#, How do I manage memory allocated - c#

On timer tick I am allocating new ClearCase ApplicationClass object, Is following code okay?
Or Do I need to release memory, If yes, How? I am using ClearCase Interop of ccauto.dll, I believe ccauto.dll is unmanaged code, I am confused, am I supposed to release the memory or not?
Please advise.
private void timer1_Tick(object sender, EventArgs e)
{
try
{
IClearCase ccNew = new ApplicationClass();
CCVOB vob = ccNew.get_VOB(ClearCaseVOB);
ccNew = null;
}
catch
{
}
}

2 comments:
according to "About CAL3" article:
Once you "GET" a ClearCase.Application object programmatically, do you need to keep getting the object in CAL?
Once the ClearCase.Application object is obtained, it can be used to get other objects
without having to create them again.
CAL ensures as best it can that CAL objects stay synchronized with the underlying ClearCase data, refreshing as necessary when invoking properties and methods.
However, the CAL objects can become invalid if someone deletes the underlying ClearCase data while a reference is still held by the CAL object.
Meaning: you could set a CCVOB instance once and for all (unless you think the Vob will disappear... which should be a very rare event!)
In C#, placing code in a using block ensures that the objects are disposed (though not necessarily collected) as soon as control leaves the block.
I am not sure if CCVOB implements Disposable, but if it does, setting it to null explicitly would prevent it to be properly disposed.
So I would not recommend ccNew = null;

Related

How I safely dispose a variable?

What is an alternate/better way I can safely dispose of the variables purge and factory in the following code?
public void Run( string XmlFragment ) {
XmlNode xmlNode = null;
try
{
xmlNode = Common.ConstructXmlNodeFromString(XmlFragment, "Params");
var list = DataList();
foreach (var item in list)
{
var factory = new PurgerFactory(item);
IPurger purge = factory.Purger;
purge.Purge();
purge = null;
factory = null;
}
Common.PurgeEmail(SuccessEmail());
}
catch (Exception ex)
{
string errorMessage = $"Purge Error: {ex.Message}. {Environment.NewLine} Stack Trace: {ex.StackTrace}";
Common.PurgeEmail(FailEmail(errorMessage));
}
}
As I think you know, C# has a garbage collector. So for normal objects that don't access an unmanaged resource, just letting the garbage collector clean them is fine.
If you want to deterministically close a managed resource the primary paradigm is inheriting from IDisposable and a using statement. This will call the Dispose function upon exiting the code block of the using statement.
If you otherwise want to clean stuff up, but you don't care when it happens you can use ~(MyType). This is called when the GC does a GC cycle, this is called the Finalizer. I personally haven't encountered a use-case for this vs IDisposable. But if you just want to make sure say a file, or otherwise is deleted when this email object is Garbage Collected, then it might be a good use case for you.
Your code doesn't indicate whether purge or factory implement IDisposable. If they do, you would call
purge.Dispose();
factory.Dispose();
or use using which ensures that Dispose is called even if the method throws an exception:
using(var factory = new PurgerFactory(item))
{
// do stuff
} // factory is disposed.
What we don't need to do is set variables to null. An object gets garbage collected sometime after there are no longer any references to it. It's true that setting factory = null removes that reference to the object, but the same thing happens anyway when the variable goes out of scope. So it's redundant.
There's really no need to try to force that to happen sooner. It's not like the object will get garbage collected the instant there are no more references to it, so we don't worry so much about that.
In this case, the variables are both declared within the foreach loop, so the references go out of scope immediately after each iteration of the loop. In other words, they already go out of scope right at the point when you're setting them to null.
That's part of what's awesome about .NET. Imagine if we had to set every reference variable to null. We'd need try/catch everywhere to make sure it happened. It would be as if every single object was disposable. What a nightmare. Instead it's handled for us in most normal scenarios so that we don't have to think about it or clutter our code with it.

implementing Dispose and Finalize for Windows phone silverlight Pages

I have a big solution with graphics, popups and animations. I have found out that I have a massive memory leak during page navigations.
Tries
I therefore tried with the first solution:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (App.RootFrame.CanGoBack)
App.RootFrame.RemoveBackEntry();
GC.Collect();
base.OnNavigatedTo(e);
}
This from several sources on MSDN and Stackoverflow, should remove the memory stored for the page. This was not the case and I am unsure if the MVVM structure of the code somehow keeps information stored. I then tried to implement deconstructors and force values to null when the event was fired like:
~SecondScreen()
{
In_Game_Crest = null;
currentViewModel = null;
}
This I did for all pages, popups and usercontrols. I then again went through the code using debug, and non of the pages deconstructor was ever fired. This has lead me on to try and use IDisposable and fiddeling around with the viewmodelLocator provided by MVVMLight, without any success.
Investigation
I have read the following addressing the issue:
StackOverFlow: Finalizer and Dispose
Finalize/Dispose pattern in C#
MSDN: Implementing a Dispose Method
MSDN: Implementing Finalize and Dispose to Clean Up Unmanaged Resources
Questions
But it has confused me more than it helped me. How should I implement the dispose and finalize methods for a page for my windows phone?
Since I'm using the MVVM structure should these methods be implemented in a ViewModel or behind the given page or both?
Examples for windows phones would be much appreciated.
Initial try with Dispose
I have read some more about the subject and found that the finalize maybe shouldn't be written? But I am still unsure. But based on this and the first MSDN link above, I tried the following:
private bool disposed = false;
public void Dispose()
{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
currentView = null;
popup = null;
Image1 = null;
Image2 = null;
}
// Release unmanaged resources. If disposing is false,
// only the following code is executed.
this.Content = null;
// Note that this is not thread safe.
// Another thread could start disposing the object
// after the managed resources are disposed,
// but before the disposed flag is set to true.
// If thread safety is necessary, it must be
// implemented by the client.
}
disposed = true;
}
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~FirstPage()
{
Dispose(false);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
this.Dispose();
base.OnNavigatedFrom(e);
}
But, but but this just made my memory increase by 23MB when I got to the second screen. This leads me to the question again, how and what should I try to implement, and WHY could the memory increase?
this = null, base.Dispose()
I have seen different implementations, either using this = null in the dispose function or using base.Dispose(). I figure that the latter can only be used if the class is IDisposable? Is this the way to go? If so how do I go about it?
Using Microsoft Profiler
So I used the profiler to verify that the FirstPage is not removed
From the above Figure it can be seen that the firstpage exists. In the comments I was told to look for the instances and reference to the elements. I therefore chose instances of firstpage and got:
Here it is confirmed that FirstPage is never destroyed. But I am stuck here, how should I interpret the data?
Hoping for some help.
It is not actually necessary to dispose when a user navigates away from a page, the performance implications of creating objects all over again is more than the memory load of having a page in the memory during when the application is alive.
You should take a decision between removing objects from the memory vis.a.vis recreating the same set of objects again.
Having said this you should be careful with the navigation model.
Memory problems might occur if you are creating objects every time the user is navigating to a page but not actually disposing when the user navigates away.
For this purpose I recommend fully understanding the PageBase and NavigationHelper or NavigationService class in your application.
You have mentioned that FirstPage is not removed from the memory during the life time of the app which according to me is ideal.
Place debug points in the potential places in your code where heavy objects might get created;
navigate a couple of times to different Pages, then come back.
Check the behavior then you might get a clear picture for yourself.
For all objects check that you manually invoke Dispose.
Dispose is a completely different concept than GarbageCollector, Dispose is just an contract that developers should adhere to by invoking it for releasing resources they perceive are no longer required to be maintained in the memory since garbage collection by the platform takes place at a indeterminate time.
In the sample you have posted I see that you are setting objects to null without actually disposing. Setting to null just changes the memory location that variable is pointing to.
It does not destroy the object immediately. an ideal dispose should be like below.
//Call on OnClosing or OnExit or similar context
protected override void Dispose(bool isDisposing)
{
if(isDisposing && !_isDisposed){
if(disposeableImage != null){
disposeableImage.Dispose();
disposeableImage = null;
}
}
}
So what I did to solve the page memory leak was using the answer at this question:
Remove Pages windows phone
There still exists some leak, which helped when removing the storyboards and eventhandlers, and adding them and removing them. But some memory is still there but no leak is occurring.

Memory Leak caused by System.Drawing.Internal.GPStream

My application keeps growing in size everytime I open and close a certain Form. I used dotTrace and came up with an ever growing list of object of type System.Drawing.Internal.GPStream which are creating byte arrays continuously without every disposing them. I did some research and found out the .net does not support any means of closing such memory streams. the following
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
if (t.IsClass && t.BaseType.Name.ToLower() == "form")
{
//Assembly ass = Assembly.GetExecutingAssembly();
object obj = null;
obj = Activator.CreateInstance(t);
Form f = new Form();
f = (Form)obj;
if ((string)f.Tag != "DNI") // Do Not Import
{
DataRow dr = Formsdt.NewRow();
dr["Name"] = f.Name;
dr["Text"] = f.Text;
dr["Tag"] = f.Tag;
Formsdt.Rows.Add(dr);
}
}
}
The intent of this code is to loop over all Forms and retrieve the controls in order to set access rights to users, activating and deactivating controls as needed programmatically.
Any insight is appreciated.
Note that
While( i am opening and closing the form)
==> Memory Allocation keeps on increasing
Somethings not being disposed of properly. Do you have warnings that say X class is iDisposable and you're not disposing it? Look into using 'using' blocks.
See this :
"A FileStream involves unmanaged resources which could actually be
immediately freed upon calling Dispose. A MemoryStream, on the other
hand, stores a managed byte array in its _buffer variable, which is
not freed at disposal time. In fact, the _buffer is not even nulled in
the MemoryStream's Dispose method, which is a SHAMEFUL BUG IMO because
nulling the reference could make the memory eligible for GC right at
disposal time. Instead, a lingering (but disposed) MemoryStream
reference still holds onto memory. Therefore, once you dispose it, you
should also null it if it's still in scope." – Triynko Oct 25 '10 at
20:46
Is a memory leak created if a MemoryStream in .NET is not closed?
Creating Forms in a loop will cause problems, depending the code in it's constructor it can fire events that will choke the message loop. Just to check, try adding an application.doevents in the loop and watch if memory gets released.
Maybe you will need to refactor your classes in order to determine access on a property that is outside a form. Something like:
Class MyObject
Public my_form as Form
Public Tag as string
end class
So you don't need to instantiate a Form.
Regards,
MarianoC.

Should Dispose() ever create new instances of objects?

Using C#.NET 4.0
My company's application makes use of a resource locker to keep records from being edited simultaneously. We use the database to store the start time of a lock as well as the user who acquired the lock. This has led to the following (strange?) implementation of dispose on the resource locker, which happens to be called from a destructor:
protected virtual void Dispose(bool disposing)
{
lock (this)
{
if (lockid.HasValue)
{
this.RefreshDataButtonAction = null;
this.ReadOnlyButtonAction = null;
try
{
**Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("#lockID", lockid.Value);
parameters.Add("#readsToDelete", null);
Object returnObject = dbio2.ExecuteScalar("usp_DeleteResourceLockReads", parameters);**
lockid = null;
}
catch (Exception ex)
{
Logger.WriteError("ResourceLockingController", "DeleteResourceLocks", ex);
}
finally
{
((IDisposable)_staleResourcesForm).Dispose();
_staleResourcesForm = null;
}
}
}
}
I am concerned about the bolded section we because have been logging strange "Handle is not initialized" exceptions from the database call. I read elsewhere that it is not safe to create new objects during Finalize(), but does the same rule apply to dispose()? Are there any possible side effects that accompany creating new objects during Dispose()?
which happens to be called from a destructor
That's the real problem. You cannot assume that the *dbio2" object hasn't been finalized itself. Finalization order is not deterministic in .NET. The outcome would look much like you describe, an internal handle used by the dbase provider will have been released so a "Handle is not initialized" exception is expected. Or the dbio2 object was simply already disposed.
This is especially likely to go wrong at program exit. You'll then also have problem when the 2 second timeout for the finalizer thread, a dbase operation can easily take more.
You simply cannot rely on a finalizer to do this for you. You must check the disposing argument and not call the dbio2.ExecuteScalar() method when it is false. Which probably ends the usefulness of the destructor as well.
Dispose is just a method, like any other method. There are some conventions about things that it should/shouldn't do, but there's nothing from the system's perspective that is wrong with creating objects in a Dispose call.
Making a DB call is a bit concerning to be personally; I wouldn't expect such an expensive and error prone activity to be called in a Dispose method, but that's more of a convention/expectation. The system won't have a problem with that.
Yes, but I would not do so unless the object created is within the local scope of the method. IDisposable is an advertisement that this class has some resource (often an unmanaged resource) that should be freed when the object is no longer used. If your Dispose is being called by your finializer (ie you are not calling the destructor directly, but waiting for the GC to do it) it can be an indication that you should be calling it earlier. You never know when the C# destructor will run, so you may be unnecessarily tying up that resource. It could also be in indication that your class doesn't need to implement IDisposable.
In your case your are using object dbio2 which I assume represents your DB connection. However, since this is called from the destructor how do you know if your connection is still valid? You destructor could an hour after your connection has been lost. You should try to ensure that this Dispose is called while you know the dbio2 object is still in scope.

static IDisposable dictionary pattern

I have a situation like below in a web application. I just wanted to check that it is a good pattern. Could something happen that meant my dictionary was corrupt (some members were disposed and some not, for example)? Have I implemented this idea correctly?
static IDictionary<string, IDisposable>() _map;
Application_Start()
{
if (_map == null)
{
_map = new IDictionary<string, IDisposable>();
_map.Add(...);
_map.Add(...);
}
}
Application_End
{
if (_map != null)
{
foreach (var m in _map)
{
m.Value.Dispose();
}
_map = null;
}
}
I see the following problem:
Removing an object from the map during the runtime of the application doesn't dispose it. You will have to do that manually. The same is true for replacing an object in the map.
UPDATE:
The following will leave undisposed objects around:
_map[key] = new DisposableObject();
The object that was previously identified by key will never be disposed.
About the whole concept:
It doesn't make too much sense. The .NET runtime frees all memory of your application when it exits. So, implementing IDisposable on objects that live as long as the application itself seems to be unneeded, unless they hold references to unmanaged resources like a open file handle.
In addition to what other people have said, there's nothing stopping someone calling Dispose on one of the objects in your dictionary - so it'd be pretty easy for you to have a mix of disposed and undisposed objects.
Of course, if you implement IDisposable properly (i.e. the object checks if it's been disposed) then it might not (but probably will) matter if objects are disposed prematurely...
I can't see that it makes much sense to do this, disposing things as the application ends won't really buy you anything as you're past the point of caring about holding onto unmanaged resources. IDisposable is more about releasing unmanaged resources as soon as possible. Greater minds might correct me, but I'm pretty sure once your application is unloaded, unmanaged resources are freed by the OS anyway.

Categories

Resources