Reputation:
how to released the resource used by the timer in the C# tried the following methods but nothing is working in my application.
t.Dispose();
t.Stop();
t.EndInit();
t.Close();
Upvotes: -1
Views: 1248
Reputation: 3414
The dispose method is there to handle closing unmanaged handles (e.g. file handles) or freeing unmanaged resources (e.g. a pointer to an external resource) in order to prevent resource leaks before garbage collection. See the official documentation for all details.
Upvotes: 0
Reputation: 3235
How do you know that it didn't work?
Dispose() should work. Can you still use the timer afterwards (you shouldn't if the it works fine)?
If you want to deallocate the memory you must call GC.Collect().
Also it's recommended to wrap the timer in a using statement (if you don't need the timer elsewhere):
using (Timer t = new Timer())
{
// Do stuff with t
}
Timer.Dispose() will be called automatically then.
Here's an example of disposing a timer:
static void TimerTest()
{
using (Timer t = new Timer(200))
{
t.Start();
t.Elapsed += new ElapsedEventHandler(t_Elapsed);
System.Threading.Thread.Sleep(5000); // Do some work here.
}
System.Threading.Thread.Sleep(5000); // Wait before closing the application
}
static void t_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Hello.");
}
Call it in your Main() method. It will print "Hello." for 5 seconds, then the timer is disposed and t_Elapsed won't be called again. After 5 more seconds the app exits.
Upvotes: 2
Reputation: 564433
I'm guessing that this is a System.Timers.Timer, given the list you have above.
You should be able to do:
t.Stop();
t.Dispose();
Once you've done this, the timer will have stopped, and its main (unmanaged) resources will have been freed. However, the resources it was using will not get cleaned up until all of the elements referred to are no longer rooted in the application, and the GC can clean them.
Make sure that your t variable is allowed to go out of scope, and anything used by your t timer is allowed to go out of scope. The GC will clean up those objects at a point when it's ready, if you do that.
Upvotes: 0