我想在线程中处理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();
}
}