Pages

Tuesday, October 12, 2010

SharePoint Long running tasks/Operations: Timer Job or SPLongOperation

When you need to perform some operations in a webpart and the operation may take few minutes, you have two options to choose from. One might be Timer job. Clicking on a button in the webpart will start the timer job and you can check the job status periodically and show the status on the page. Timer job is perfect for long running operation but showing status in UI while the job is running might be a bit hard.

Another option might be to use SPLongOperation class of SharePoint to run long operation while to show user meaningful message. SPLongOperation is a good choice when you want to run an operation that takes few minutes only and when the user is trusted ( I mean the user is trusted to wait while the operation in progress by seeing the wait screen rather than refreshing the page). As shown in the following code snippet, you can create a SPLongOperation instance and put the long running code between SPLogOperation.Begin() and SPLongOperaiton.End() method invocation. In the end operation you need to specify the url the page will be redirected to once the operation is done. This might be the same page url or different page’s url.

var longOperation=new SPLongOperation(this.Page);
longOperation.LeadingHTML = "Please wait while the operation is running";
longOperation.TrailingHTML = "Once the operation is finished you will be redirected to result page";
longOperation.Begin();

//Do long operation here
Thread.Sleep(10000);

longOperation.End("Result.aspx");

As as result of the above code you can see the following screen during the operation is progress.

image

 

Even when you are not sure how much time a page takes to load you can use the SPLongOperation interface which may provide better user experience. So if your operation needs several minutes or more your choice might be Timer job. But the operation takes few minutes and the operation needs user interaction then you can opt to use SPLongOperation.

1 comment:

  1. Hello!
    Nice article, but it doesn't take into account ThreadAbortException, which is sometimes thrown. I have a similar article in my blog and I explained the reason of ThreadAbortException. Unlike this post, my article is concerning SP2007, but I believe, that SPLongOperation wasn't changed thoroughly. The article is here - http://dotnetfollower.com/wordpress/2011/08/sharepoint-how-to-use-splongoperation/
    Thanks!

    ReplyDelete

Note: Only a member of this blog may post a comment.