我正在开发一个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
以上所有代码都发生在同一个类中。只有事件处理函数在其他类中 完成后我需要杀死我的线程吗? 如果我做错了,请建议我。
答案 0 :(得分:1)
在ASP.NET应用程序中使用ThreadPool
的正确方法是not to use it。 ASP.NET本身使用相同的ThreadPool
,因此每当您对工作项进行排队时,就会占用ASP.NET实际提供页面所需的资源。
为了完整起见,我将补充一点,“首选”替代方案是简单地为作品创建标准Thread
。您将不得不更加防御性地编写工作方法,因为裸线程与ThreadPool
线程没有相同的保护级别,但只要您这样做,那么您将是安全的并且不会蚕食ASP.NET请求。
答案 1 :(得分:1)
如果要异步触发事件,只需在每个代理上调用BeginInvoke即可。无需将其排队为工作项。
答案 2 :(得分:0)
我认为ASP.NET MVC 2中有AsyncController你应该利用而不是直接使用ThreadPool,