C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
DisposableAction in C#
WhatsApp
James Croft
Jun 17
2015
9.6
k
0
0
A disposable action allows the developer to use it as part of a using statement to call a function on creation and another on disposal. Good for setting Boolean values to stop your app doing something while you're within the using statement.
Used as part of the Microsoft Band development series.
namespace
Croft.MicrosoftBand.Common
{
using
System;
/// <summary>
/// The disposable action.
/// </summary>
public
class
DisposableAction : IDisposable
{
private
Action _dispose;
/// <summary>
/// Initializes a new instance of the <see cref="DisposableAction"/> class.
/// </summary>
/// <param name="dispose">
/// The dispose.
/// </param>
public
DisposableAction(Action dispose)
{
if
(dispose ==
null
)
throw
new
ArgumentNullException(
"dispose"
);
this
._dispose = dispose;
}
/// <summary>
/// Initializes a new instance of the <see cref="DisposableAction"/> class.
/// </summary>
/// <param name="construct">
/// The construct.
/// </param>
/// <param name="dispose">
/// The dispose.
/// </param>
public
DisposableAction(Action construct, Action dispose)
{
if
(construct ==
null
)
throw
new
ArgumentNullException(
"construct"
);
if
(dispose ==
null
)
throw
new
ArgumentNullException(
"dispose"
);
construct();
this
._dispose = dispose;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public
void
Dispose()
{
this
.Dispose(
true
);
GC.SuppressFinalize(
this
);
}
/// <summary>
/// The dispose.
/// </summary>
/// <param name="disposing">
/// The disposing.
/// </param>
protected
virtual
void
Dispose(
bool
disposing)
{
if
(disposing)
{
if
(
this
._dispose ==
null
)
{
return
;
}
try
{
this
._dispose();
}
catch
(Exception ex)
{
// ToDo: Log error?
}
this
._dispose =
null
;
}
}
}
}
IDisposable
Action
DisposableAction
C#
Up Next
DisposableAction in C#