【问题标题】:Am I using ThreadPool.QueueUserWorkItem properly?我是否正确使用 ThreadPool.QueueUserWorkItem?
【发布时间】:2010-12-31 12:45:26
【问题描述】:

我正在开发一个 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

以上所有代码都发生在同一个类中。只有事件处理函数在其他类中 完成后我需要杀死我的线程吗? 如果我做错了什么,请建议我。

【问题讨论】:

  • 只调用“Invoke”怎么样?

标签: c# asp.net-mvc multithreading queueuserworkitem


【解决方案1】:

我认为 ASP.NET MVC 2 中有 AsyncController,您应该利用它而不是直接使用 ThreadPool,

【讨论】:

    【解决方案2】:

    在 ASP.NET 应用程序中使用ThreadPool 的正确方法是not to use it。 ASP.NET 本身使用相同的ThreadPool,因此每当您将工作项排队时,都会占用 ASP.NET 实际服务页​​面所需的资源。

    为了完整起见,我要补充一点,“首选”替代方案是简单地为工作创建一个标准Thread。您将不得不更加防御性地对工作方法进行编码,因为裸线程没有与ThreadPool 线程相同的保护级别,但只要您这样做,您就会安全并且不会蚕食 ASP。 NET 请求。

    【讨论】:

      【解决方案3】:

      如果您想异步触发事件,您只需在每个委托上调用 BeginInvoke。无需将其作为工作项排队。

      【讨论】:

      • 如果我使用 BeginInvoke,我也必须调用 EndInvoke,我不想这样做
      猜你喜欢
      • 2016-01-24
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      相关资源
      最近更新 更多