I am a farily new .NET-developer and I'm currently reading up on async
/await
. I need to work on a framework used for testing devices that are controlled by remotely accessing servers using TCP and reading/writing data from/to these servers. This will be used for unit tests.
There is no application-layer protocol and the server may send data based on external events. Therefore I must be able to continuously capture any data coming from the server and write it to a buffer, which can be read from a different context.
My idea goes somewhere along the lines of the following snippet:
// ...
private MemoryStream m_dataBuffer;
private NetworkStream m_stream;
// ...
public async void Listen()
{
while (Connected)
{
try
{
int bytesReadable = m_dataBuffer.Capacity - (int)m_dataBuffer.Position;
// (...) resize m_dataBuffer if necessary (...)
m_stream.ReadTimeout = Timeout;
lock (m_dataBuffer)
{
int bytesRead = await m_stream.ReadAsync(m_dataBuffer.GetBuffer(),
(int)m_dataBuffer.Position, bytesReadable);
m_stream.Position += bytesRead;
}
}
catch (IOException ex)
{
// handle read timeout.
}
catch (Exception)
{
throw new TerminalException("ReadWhileConnectedAsync() exception");
}
}
}
This seems to have the following disadvantages:
- If calling and awaiting the
Listen
function, the caller hangs, even though the caller must be able to continue (as the network stream should be read as long as the connection is open). - If declaring it
async void
and not awaiting it, the application crashes when exceptions occur in the Task. - If declaring it
async Task
and not awaiting it, I assume the same happens (plus I get a warning)?
The following questions ensue:
- Can I catch exceptions thrown in
Listen
if I don't await it? - Is there a better way to constantly read from a network stream using
async
/await
? - Is it actually sane to try to continuously read from a network stream using
async
/await
or is a thread a better option?