Wednesday, November 12, 2008

SPLongOperation and Threadabortexception

SPLongOperation allows you to show the nice SharePoint spinner page when you have code in a SharePoint application page which runs for quite a while  (See for example Compiling SharePoint 2007 audiences using the SharePoint object model (C# code sample) ). Unfortunately there is not a lot of documentation about it the use of it out there. So when I stumbled upon a ThreadAbortException when trying to create a new SharePoint site in my application page. Apparently the only way around it was adding an empty Catch block... Maybe this is because internally SPLongOperation uses Response.End internally (See http://support.microsoft.com/kb/312629 ) but I'm not sure. Can anyone confirm that this is the way to go?

try
{
string sRedirectUrl = "http://moss";

using (SPLongOperation operation = new SPLongOperation(this.Page))
{
operation.Begin();

using (SPSite sitecollection = new SPSite("http://moss"))
{
using (SPWeb toplevelsite = sitecollection.OpenWeb())
{
toplevelsite.AllowUnsafeUpdates = true;
toplevelsite.Update();

using (SPWeb newsite = toplevelsite.Webs.Add("demo", "demo", "",

Convert.ToUInt32(1043), "STS#0", false, false))
{
//TODO Add some extra stuff in here ...
sRedirectUrl = newsite.Url;
}
}
}
operation.End(sRedirectUrl);
}

}
catch (ThreadAbortException tex) { }
catch (Exception ex)
{
SPUtility.TransferToErrorPage(ex.ToString());
}






3 comments:

Gary Lapointe said...

The ThreadAbortException happens when you call Response.End() as the support article mentions (the SPLongOperation does this in the End() method) - I've always just rethrown the exception if I wasn't in control of the code doing the redirect - basically, let the framework handle it.

Paul Schaeflein said...

That is how I do it.

dotNetFollower said...

Hello!
I have a similar article in my blog, where the reason of ThreadAbortException is described a bit more in details. The article is here - http://dotnetfollower.com/wordpress/2011/08/sharepoint-how-to-use-splongoperation/
Thanks!