I am trying to re-write an asynchronous TCP class I once wrote implementing the new await/async construct.
So far I have
public async void Send(byte[] data)
{
await SendAsync(data);
}
private Task SendAsync(byte[] data)
{
var stream = _tcpClient.GetStream();
return new Task(()=>stream.Write(data, 0, data.Length));
}
but something smells odd. Is this the correct way of doing it?
Edit:
For instance, I could achieve the same with
public async void Send(byte[] data)
{
await SendAsync(data);
var stream = _tcpClient.GetStream();
await Task.Factory.StartNew(()=>stream.Write(data, 0, data.Length));
}
or using Task.Run(..)
which is preferred?
Use the Stream.WriteAsync() method instead and transfer the work of handling asynchronicity onto the base class library. There is also a ReadAsync for code not included in the example above.