TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
DisposableAction in C#
James Croft
Jun 17
2015
Code
9.1
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
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#