2010-10-05 41 views
0

目前我正在寫一個小型網絡服務器,併爲服務器獲取的每個請求創建一個新的線程。 基本上是這樣的:如何在線程中封裝一個方法?

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-directive中發生的事情。我想到的方法等:

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

的問題是,我需要太轉移上下文對象,但我不知道該怎麼辦呢線程安全的,這將是最好的方式。我想過創建一個從Thread派生的新類,並實現了ProcessRequest方法和新的EncapsulateMe方法。這會對我想要完成的事情複雜嗎?

編輯:我剛剛發現,它不可能寫在c#中的類從Thread派生,因爲這個類是密封的...有沒有什麼辦法在c#中創建自己的線程? 我只知道這個從Java,所以我有點糊塗了,這不是在C#中可能...

回答

0

我試圖組成一個新的類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; 
    } 
} 

但我我對這個解決方案並不滿意......這對我來說似乎有點不可思議。任何人有一個更小/更好的想法?