WPF:如何在线程中编写主进程拥有的流?

时间:2012-05-24 12:21:15

标签: c# wpf multithreading stream

我想实现这个功能:当收到http请求时,然后创建一个新的窗口表单,并等待用户输入响应文本并写入http响应流。问题是,即使我使用Action<>,我也无法在线程中向流写入响应文本。代表。一些代码如下:

public partial class MainWindow : Window
{
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //startup web server 
        Dispatcher.BeginInvoke(new Action(Start));
    }

    private void Start()
    {
        var server = new HttpServer();
        try
        {
            server.EndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80);
            server.Start();
            server.RequestReceived += DataProcess;
        }
        catch (Exception ex)
        {
            return;
        }
    }

    private void DataProcess(object sender, HttpRequestEventArgs e)
    {
        //create a new window in which user can input the response for the http request e.
        var pw = (PrivateWindow)Dispatcher.Invoke(new Func<HttpRequestEventArgs, PrivateWindow>(CreatePrivateWindow), e);
    }

    public PrivateWindow CreatePrivateWindow(string windowKey, HttpRequestEventArgs e)      
    {
        var pw = new PrivateWindow(); 
        pw.httpRequest = e;//pass the stream to thread here.       
        windows.Add(pw);
        return pw;    
    }
}

public partial class PrivateWindow : Window
{
    private void btnSendMessage_Click(object sender, RoutedEventArgs e)
    {
        string messageText = new TextRange(txtWriteMessage.Document.ContentStart, txtWriteMessage.Document.ContentEnd).Text.Trim(); 
        //write the response in thread           
        Dispatcher.BeginInvoke(new Action<HttpRequestEventArgs, string>(WriteToStream), httpRequest, messageText);
    }
    private void WriteToStream(HttpRequestEventArgs e, string str)
    {
        //**here occurs "stream can not be written" error.** 
        using (var writer = new StreamWriter(e.Response.OutputStream))
        {
            writer.Write(str);
        }
    }
} 

0 个答案:

没有答案