Use the thread pool in ASP.NET

by Mads Kristensen 15. January 2007 00:47

The thread pool gives you an easy and safe way for creating multithreaded applications, and even though the stateless nature of the Internet isn’t the best place for multithreading, it can still be the right thing to do for certain scenarios.

I’ve seen a lot of examples on how to use the thread pool and none of them takes advantage of the Boolean return value of the QueueUserWorkItem method. This is important because if the thread pool fails to create a new thread you will not be notified about it. Here is a short example of a button’s click event handler that creates a new thread to do some work.

protected void btnSave_Click(object sender, EventArgs e)

{

  if (System.Threading.ThreadPool.QueueUserWorkItem(ThreadProc))

  {

    Response.Write("Processing is started successfully.");

  }

  else

  {

    Response.Write("An error occured.");

  }

}

 

private void ThreadProc(object stateInfo)

{

  DoSomething();

}

By using the Boolean return value we can now catch the failure and notify the user or maybe try again.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

ASP.NET

Comments

1/16/2007 10:22:56 PM #

 Michal Talaga

From MSDN documentation on the QueueUserWorkItem:

Return Value
true if the method is successfully queued; OutOfMemoryException is thrown if the work item could not be queued.

From this sentence it seams that you don't have to check the return value since it will either be success (true) or none at all (exception).
Keeping in mind that Microsoft's documentation is not always accurate, I wonder if it is possible to get false from this method.
Unfortunately Reflector will not answer this question since the important part of the code is defined as "extern".
So we have 2 choices: either trust the documentation which says that exception will occur or we can trust the api which suggests both the true and the false are valid options for the returned value. Checking it doesn't hurt much btw.
My general motto is: better safe than sorry.

Michal Talaga |

1/16/2007 10:58:56 PM #

Mads Kristensen

I like that motto Smile

Mads Kristensen |

4/14/2008 9:38:13 PM #

Ugur

"Response.Write("Processing is started successfully.");"

this line not working? thread working succesfully but i can't see message on page?

Ugur Turkey |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008