代码之家  ›  专栏  ›  技术社区  ›  Philipp M

如何将线程封装到方法中?

  •  0
  • Philipp M  · 技术社区  · 14 年前

    目前,我正在编写一个小型Web服务器,并为服务器收到的每个请求创建一个新线程。 基本上是这样的:

    public class MyController
    {
        public void ProcessRequest(object contextObject)
        {
          HttpListenerContext context = (HttpListenerContext)contextObject;
    
          // handle request
          if (someCondition())
          {
            context.Response.StatusCode = 400;
            context.Response.StatusDescription = "Missing something";
          }
          else
          {
            context.Response.StatusCode = 200;
            context.Response.StatusDescription = "Everything OK";
          }
        }
    
        public void AcceptRequest()
        {
          while (true)
          {
            HttpListenerContext context = HttpListener.GetContext();
            Thread thread = new Thread(this.ProcessRequest);
            thread.Start(context);
          }
        }
    }
    

    我尽量使我的例子简单明了。显然,在我的应用程序中,它有点复杂。 现在我尝试封装if else指令中发生的事情。我想到了这样一种方法:

    public void EncapsulateMe(int code, string description)
    {
      context.Response.StatusCode = code;
      context.Response.StatusDescription = description;
    }
    

    编辑:我刚刚发现用c语言编写一个派生自的类是不可能的 Thread

    1 回复  |  直到 11 年前
        1
  •  0
  •   Philipp M    14 年前

    我尝试用一个线程组成一个新类ProcessRequestThread:

    public class ProcessRequestThread
    {
      private Thread ProcessThread;
      private HttpListenerContext Context;
    
      public ProcessRequestThread()
      {
        ProcessThread = new Thread( ProcessRequest );
        ProcessThread.Start();
      }
    
      private void ProcessRequest(object contextObject)
      {
        Context = (HttpListenerContext)contextObject;
    
        // handle request
        if (someCondition())
        {
          EncapsulateMe(400, "Missing something");
        }
        else
        {
          EncapsulateMe(200, "Everything OK");
        }
      }
    
      private void EncapsulateMe(int code, string description)
      {
        Context.Response.StatusCode = code;
        Context.Response.StatusDescription = description;
      }
    }
    

    但我对这个解决方案并不满意。。。对我来说似乎很重要。有人有更小/更好的主意吗?