我是否正确使用 ThreadPool.QueueUserWorkItem ?
我正在开发 ASP.NET MVC 应用程序。 我想在事件发生时生成几个线程,我不关心返回值 我的线程,我想进行异步调用,所以我使用 ThreadPool.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); }
);
}
}
}
我已将事件处理函数附加到事件,
这就是我引发事件的方式,
this.SomeEventhappened(userProfile); //Here the event is raised
所有上述代码都发生在同一个类中。只有事件处理函数位于其他类中 我需要在线程完成后终止它们吗? 如果我做错了什么,请建议我。
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 ThreadPool.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想异步触发事件,您只需在每个委托上调用 BeginInvoke 即可。无需将其作为工作项排队。
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.
在 ASP.NET 应用程序中使用 ThreadPool 的正确方法是 不使用它。 ASP.NET 本身使用相同的
ThreadPool
,因此每当您对工作项进行排队时,您都会拿走 ASP.NET 实际提供页面所需的资源。为了完整起见,我将补充一点,“首选”替代方案是简单地为工作创建一个标准
Thread
。您必须更加防御性地编写工作方法,因为裸线程没有与 ThreadPool 线程相同级别的保护,但只要您这样做,您就会安全并获胜不会蚕食 ASP.NET 请求。The correct way to use the
ThreadPool
in an ASP.NET application is not to use it. ASP.NET itself uses the sameThreadPool
, 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 aThreadPool
thread, but as long as you do this then you'll be safe and won't cannibalize ASP.NET requests.我认为 ASP.NET MVC 2 中有 AsyncController 你应该利用它而不是直接使用 ThreadPool,
I think there is AsyncController in ASP.NET MVC 2 which you should take advantage of instead of using directly the ThreadPool,