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?
Thanks for every hints, leads, answers or pointer in the right direction :)
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#...