开发者

Am I using ThreadPool.QueueUserWorkItem properly?

I am working on a ASP.NET MVC app. I wanted to spawn few threads when a event occurs, I dont care for the return value of my threads and I wanted to make a async call so I am using Th开发者_开发知识库readPool.QueueUserWorkItem ,

 public event SomeEventHandler SomeEvent;

private void SomeEventhappened(UserProfile arg)
        {
          SomeEventHandler handler = SomeEvent;
          if (handler != null)
          {
            // handler(currentUser);
            foreach (SomeEventHandler wc in handler.GetInvocationList())
            {
              SomeEventHandler wc2 = wc;
              ThreadPool.QueueUserWorkItem(
                    delegate { wc2(arg); }
               );
            }
          }
        }

I have attached the event handler function to the event

This is how I raise the event,

this.SomeEventhappened(userProfile);   //Here the event is raised

All the above code is happening in the same class. Only the event handler functions are in other class Do I need to kill my threads after they complete? Please suggest me if I am doing something wrong.


If you want to fire your event asynchronously you can simply call BeginInvoke on each delegate. There is no need to queue it as a work item.


The correct way to use the ThreadPool in an ASP.NET application is not to use it. ASP.NET itself uses the same ThreadPool, so whenever you queue a work item, you are taking away resources that ASP.NET needs to actually serve pages.

For the sake of completeness, I'll add that the "preferred" alternative would be to simply create a standard Thread for the work. You will have to code the work method more defensively, as a bare thread does not have the same level of protection as a ThreadPool thread, but as long as you do this then you'll be safe and won't cannibalize ASP.NET requests.


I think there is AsyncController in ASP.NET MVC 2 which you should take advantage of instead of using directly the ThreadPool,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜