gpt4 book ai didi

c# - 如何处理对同一个套接字的读取和写入

转载 作者:太空宇宙 更新时间:2023-11-03 13:06:49 25 4
gpt4 key购买 nike

我建立了到我的套接字服务器的连接,然后开始大量读取和写入数据。立即发生异常:

mscorlib.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理

附加信息:该流当前正被流上的先前操作使用。

我怎样才能检测到

_reader.ReadLineAsync();

目前正在接收一些数据,我应该等待写入,反之亦然?

这个类被客户端使用,它基本上将从服务器接收到的数据发送回服务器。

public class TcpClientWorker2 
{
private TcpClient _client;
private Thread _t;
private NetworkStream _networkStream;
private StreamWriter _writer;
private StreamReader _reader;
public TcpClientWorker2()
{
var ipHostInfo = Dns.Resolve(Dns.GetHostName());
var ipAddress = ipHostInfo.AddressList[0];

_client = new TcpClient();
_client.Connect(ipAddress, 10000);
_t = new Thread(Run);
}

public async void Run()
{
_networkStream = _client.GetStream();
_reader = new StreamReader(_networkStream);
_writer = new StreamWriter(_networkStream) { AutoFlush = true };
while (true)
{
var data = await _reader.ReadLineAsync();
//perform callback (send the data immediately back to server)
}
}

public void Start()
{
_t.Start();
}
public async Task Send(string text)
{
await _writer.WriteLineAsync(text);
}
}

最佳答案

从这个来源你得到确认: https://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.

我们可以在你的代码中看到只有一个线程在读,但是在你的代码中没有确认只有一个线程在写。这是您应该进一步调查的部分。

关于c# - 如何处理对同一个套接字的读取和写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30536106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com