Search code examples
c#multithreadingencapsulation

How to encapsulate from a thread in a method?


Currently I'm writing a little webserver and I create a new Thread for every request the server gets. Basically it's like this:

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);
      }
    }
}

I tried to keep my example simple. Obviously in my application it's a bit more complicated. Now I try to encapsulate what here happens in the if-else-directive. I thought about a method like:

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

The problem is that I need to transfer the context object too, but I'm not sure how to do it thread-safe and what would be the best way. I thought about creating a new class that derives from Thread and implements the ProcessRequest-method and the new EncapsulateMe-method. Would that be to complicated for what I'm trying to accomplish?

Edit: I just found out that it's not possible to write a class in c# that derives from Thread because this class is sealed... is there any way to create your own Threads in c#? I just knew this from Java, so I'm a bit confused that it's not possible in c#...


Solution

  • I tried to compose a new class ProcessRequestThread with a Thread:

    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;
      }
    }
    

    But I'm not really satisfied with this solution... it seems somehow to much to me. Anyone got a smaller/better idea?