我想在線程中處理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();
}
}
爲什麼你不能寫流?是否有例外?如果是這樣的話,什麼信息?如果不是,那意外的行爲是什麼? – phoog
e.Response.OutputStream很可能超出了範圍並被丟棄。 –
@phoog:消息是「無法訪問封閉的流」。 –