Want to become a Vibe Coder? Join Vibe Coding Training here
x
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
Diffrent Ways to Implement Dispose Patterns/Methods in Your SharePoint Code
WhatsApp
Laxman Vyavahare
10y
3.2
k
0
1
25
Blog
Introduction
It’s very important to dispose our objects in SharePoint to avoid
Memory Leaks
, this article will explain dispose Patterns or methods in SharePoint code.
Method 1
- Manually calling Dispose()
The most general and simple approach to dispose your objects is to simply call the .Dispose() method of your objects:
SPSite site =
new
SPSite (
"http://laxman-sharepoi:1000/admin/"
);
// Do stuff
site.Dispose();
Method 2 - Encapsulating the statement in a using() block
A more common approach is to encapsulate the code in a using-block where the object will be automatically disposed when we are reaching the end of our block.
using
(SPSite site =
new
SPSite (
"http://laxman-sharepoi:1000/admin/"
));
{
// Do stuff
}
Method 3 - Utilize a try/finally block
Whenever you are expecting to catch an exception and need to handle them – a better approach for disposing is to create a try-finally block and dispose the object in the finally-block.
Sample
1: Without exception handling.
SPSite site =
null
;
try
{
site =
new
SPSite (
"http://laxman-sharepoi:1000/admin/"
);
// do stuff
}
finally
{
if
(site!=
null
) site.Dispose();
}
Sample 2
: With exception handling.
SPSite site =
null
;
try
{
site =
new
SPSite (
"http://laxman-sharepoi:1000/admin/"
);
// do stuff
}
catch
(Exception ex)
{
// Handle the exception
// Possibly genrate logs
}
finally
{
if
(site!=
null
) site.Dispose();
}
Method 4
- A mix mode approach
In some scenarios it might be a necessity to use mix oapproach for disposing.
using
(SPSite site =
new
SPSite (
"http://laxman-sharepoi:1000/admin/"
))
{
foreach
(SPSite site
in
site.WebApplication.Sites)
{
try
{
// Do stuff
}
catch
(Exception ex)
{
// Log and handle exceptions
}
finally
{
if
(site!=
null
) site.Dispose();
}
}
}
People also reading
Membership not found