开发者

Basic multithreading with StreamReader/StreamWriter

I'm using a StreamReader to read from a TcpSocket, and a StreamWriter to write to that TcpSocket. I would like to have the reading code in one thread and the writing code in another. How do I do this in a thread-safe manner?

If I do the following, then I guess the writer thread will be blocked in many cases:

lock (tcpClient) {
    streamReader.ReadLine();
}

Here would be the writer code:

lock (tcpClient) {
    streamWriter.WriteLine(line);
}
开发者_JAVA技巧


It is safe to send on one thread and receive on the other thread.

So you can do this in one thread:

streamReader.ReadLine();

and this in another thread:

streamWriter.WriteLine(line);

without having to lock the tcpClient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜