How to abort socket's BeginReceive()?

后端 未结 7 2047
夕颜
夕颜 2020-12-05 06:17

Naturally, BeginReceive() will never end if there\'s no data. MSDN suggests that calling Close() would abort BeginReceive().

7条回答
  •  执笔经年
    2020-12-05 06:54

    I was struggling with this as well but as far as I can tell using a simple boolean flag before calling .BeginReceive() will work as well (so there'll be no need for exception handling). Since I already had start/stop handling, this fix was a matter of one if statement (scroll down to the bottom of the OnReceive() method).

    if (_running)
    {
        _mainSocket.BeginReceive(_data, 0, _data.Length, SocketFlags.None, OnReceive, null);
    }                
    

    Should I have overlooked something with this approach, let me know!

提交回复
热议问题