I wrote extension method to Timer class to destroy it after certain amount of time. seems like it actually only set false in timer.enable fields but don’t really set the whole things to false. Is there a way to nullify an object from it own extension method?
and another thing – is it good practice to implement it in that way or I should expect sync issues and more surprises?
timer.DestroyAfter(1.Hours()) :
public static void DestroyAfter(this Timer timer, TimeSpan timeSpan)
{
var killingTimer = new Timer(timeSpan.TotalMilliseconds)
{
AutoReset = false,
};
killingTimer.Elapsed += (sender, e) =>
{
timer.Stop();
**timer = null;** //doesn't seem to work though line is executed
killingTimer.Stop();
killingTimer = null;
};
killingTimer.Start();
}
This would only be possible if the “this” parameter was also a ref parameter, which it is not.
So the answer is no (in the current C# implementation)
Regarding your other question: there’s nothing wrong with the way you implemented it (stopping the timer and clearing the reference to the captured “killingTimer” variable).