2012-05-15 23 views
1

我想在線程中處理http請求,代碼如下,其中的問題是OutputStream(如代碼所示)無法寫入。當我把這個過程放在主線程中時,這沒有問題。你能給我任何建議嗎?爲什麼不能在線程中讀寫數據流

public partial class MainWindow : Window 
    { 
     private void Window_Loaded(object sender, RoutedEventArgs e) 
     { 
      var server = new HttpServer(); 
      try 
      { 
       server.EndPoint = new IPEndPoint(127.0.0.0, 80); //set webServer para 
       server.Start(); //start webServer 
       server.RequestReceived += server_RequestReceived; //register the event 
      } 
      catch (Exception ex) 
      { 
       return; 
      } 
     } 
     private void server_RequestReceived(object sender, HttpRequestEventArgs e) 
     { 
      var dataProcess = new Action<HttpRequestEventArgs>(DataProcess); 
      Dispatcher.BeginInvoke(dataProcess,e); //start thread 
     } 
     private void DataProcess(HttpRequestEventArgs e) 
     { 
      StreamReader sr = new StreamReader(@"c:\test.txt"); 
      string text = sr.ReadToEnd(); 
      using (var writer = new StreamWriter(e.Response.OutputStream)) //**Cannot write stream** 
      { 
       writer.Write(text); 
      } 
      sr.Close(); 
     } 
    } 
+0

爲什麼你不能寫流?是否有例外?如果是這樣的話,什麼信息?如果不是,那意外的行爲是什麼? – phoog

+1

e.Response.OutputStream很可能超出了範圍並被丟棄。 –

+0

@phoog:消息是「無法訪問封閉的流」。 –

回答

1

我認爲您的請求正在關閉之前,新線程運行。你可以做的是在新線程中執行整個請求。喜歡的東西:

public partial class MainWindow : Window 
{ 
    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     var start = new Action<HttpRequestEventArgs>(Start); 
     Dispatcher.start(start,e); //start thread 
    } 

    private void Start(HttpRequestEventArgs e) 
    { 
     var server = new HttpServer(); 
     server.EndPoint = new IPEndPoint(127.0.0.0, 80); //set webServer para 
     server.Start(); //start webServe 
     server.RequestReceived += server_RequestReceived; //register the event 
    } 

    private void server_RequestReceived(object sender, HttpRequestEventArgs e) 
    { 
     StreamReader sr = new StreamReader(@"c:\test.txt"); 
     string text = sr.ReadToEnd(); 
     using (var writer = new StreamWriter(e.Response.OutputStream)) //**Cannot write stream** 
     { 
      writer.Write(text); 
     } 
     sr.Close(); 
    } 
} 
+0

你說得對,ivowiblo。謝謝 –

0

大多數likley e.Response.OutputStream是隻寫流包含從服務器接收響應。

根據你想要做什麼,你可以寫請求流或從OutputStream讀取。

注意:您正在使用一些自定義類,因此建議純粹基於方法名稱。

相關問題