NetCoreServer icon indicating copy to clipboard operation
NetCoreServer copied to clipboard

_receiveBuffer is not thread safe when called from OnAsyncCompleted->ProcessReceive->OnReceived

Open unununon opened this issue 3 years ago • 6 comments

there is no lock on it,so Is there a problem that When i m dealing with the data in OnReceived,then the data changed by other thread?

unununon avatar Mar 13 '22 06:03 unununon

_receiveBuffer does not require locking, it should not be used in multithread. Please check the whole cycle:

ReceiveAsync() -> TryReceive() -> Socket.ReceiveAsync() -> OnAsyncCompleted() -> ProcessReceive() -> OnReceived() -> TryReceive() -> ...

chronoxor avatar Mar 13 '22 06:03 chronoxor

Thx @chronoxor ,but I m working with TCP async workflow,and as you mentioned,I should call receive or receiveAsync manually only in sync workflow. So I think the correct async workflow entry is from SocketAsyncEventArgs.Complete‘s callback->OnAsyncCompleted->ProcessReceive->OnReceived. Iocp will callback with a random thread in threadpool in theory(also i have tested it).So I still think there will be some problem here.

unununon avatar Mar 13 '22 07:03 unununon

In sync mode you should call only sync methods - Connect(), Disconnect(), Send(), Receive(). I suggest use sync scenarios only for TCP/SSL client.

For server I suggest considering async processing. As a reference please see async TcpChatServer

chronoxor avatar Mar 13 '22 08:03 chronoxor

TcpServer.Start() will start socket accepting and will call TcpSession.TryReceive() automatically for each connected session.

chronoxor avatar Mar 13 '22 08:03 chronoxor

Iocp will callback with a random thread in threadpool in theory(also i have tested it).So I still think there will be some problem here.

Yes receiving loop will be called on a threadpool, but sequentially, so you'll never get _receiveBuffer be used in several threads at the same time, only one by one.

chronoxor avatar Mar 13 '22 08:03 chronoxor

I see,Thanks for your explaining.

unununon avatar Mar 13 '22 08:03 unununon