开发者

Basic multithreading with StreamReader/StreamWriter

开发者 https://www.devze.com 2023-03-26 00:52 出处:网络
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 i

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

精彩评论

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