Thursday, October 1, 2009

SPLongOperation class

Scenario:
I am trying to create a site collection from an aspx, and I am getting a “Thread was being aborted” exception .. works just fine from a console app.

Error : Thread was being aborted

Solution:
As you have seen that this error is specific to ASPX and when the code can take good amount of time to execute, You will need to use SPLongOperation class.

Creating a Web Application / Site Collection / Site can take good amount of time and other operation like attaching a Workflow to a list item using ASPX, you might get this error in ASPX page.

Then how the hell Microsoft was able to do it.

Code:

SPLongOperation operation = new SPLongOperation(this.Page);

operation.Begin();

// do long operation code here...
System.Threading.Thread.Sleep(6000);

//operation.End("http://localhost/_layouts/success.aspx");
// updated as per gautam's suggestion
operation.End("http://localhost/_layouts/success.aspx", Microsoft.SharePoint.Utilities.SPRedirectFlags.DoNotEndResponse, HttpContext.Current, "");
Article:
Example

3 comments:

Gautam Kaikini,  March 31, 2010 at 8:19 AM  

Hi Sandeep,

If you use this code:
operation.End("http://localhost/_layouts/success.aspx", Microsoft.SharePoint.Utilities.SPRedirectFlags.DoNotEndResponse, HttpContext.Current, "");

Then,you will NOT get the "Thread was being aborted" error.

--
I am a SharePoint Developer and I like your blog very much.
It is extremely useful and informative.

Keep posting...

Sandeep March 31, 2010 at 9:00 AM  

Thanks Gautam , I have updated the post as per your suggestion.

I am happy that you liked the blog :)

dotNetFollower August 11, 2011 at 4:31 PM  

Hello!I believe that SPRedirectFlags.DoNotEndResponse is ignored. It makes sense only if SPLongOperation.End would call Response.Redirect, but it doesn't. Redirection is accomplished through JavaScript. I've mentioned about this fact in my blog here - http://dotnetfollower.com/wordpress/2011/08/sharepoint-how-to-use-splongoperation/.
Thanks!