You need to change your DataFeed
class to support that. You'll just have to use the task asynchronous pattern in there. That means that all the asynchronous methods in DataFeed
have to return a Task
(or some Task<T>
), and they should be named ConnectAsync
(for example).
Now, with Socket
, this isn't entirely easy, because the XXXAsync
methods on Socket
aren't actually awaitable! The easiest way is to simply use TcpClient
and TcpListener
respectivelly (provided you're using TCP):
public async Task<bool> LoginAsync(TcpClient client, ...)
{
var stream = client.GetStream();
await stream.WriteAsync(...);
// Make sure you read all that you need, and ideally no more. This is where
// TCP can get very tricky...
var bytesRead = await stream.ReadAsync(buf, ...);
return CheckTheLoginResponse(buf);
}
and then just use it from the outside:
await client.ConnectAsync(...);
if (!(await LoginAsync(client, ...))) throw new UnauthorizedException(...);
// We're logged in
This is just sample code, I assume you're actually able to write decent TCP code to start with. If you do, writing it asynchronously using await
isn't really much harder. Just make sure you're always awaiting some asynchronous I/O operation.
If you want to do the same using just Socket
, you will probably have to use Task.FromAsync
, which provides a wrapper around the BeginXXX
/ EndXXX
methods - very handy.