How to convert this code to async waiting?

I have many such codes:

        var feed = new DataFeed(host, port);
        feed.OnConnected += (conn) =>
        {
            feed.BeginLogin(user, pass);
        };
        feed.OnReady += (f) =>
        {
             //Now I'm ready to do stuff.
        };

        feed.BeginConnect();

As you can see, I use the usual way of performing asynchronous operations. How do I change this code to use async await? Preferably something like this:

public async void InitConnection()
{
    await feed.BeginConnect();
    await feed.BeginLogin(user, pass);

    //Now I'm ready
}
+4
source share
2 answers

You can use TaskCompletionSource<T>to wrap EAP (event-based asynchronous pattern) in Tasks. It is not clear how you handle errors and cancel operations in your DataFeed class, so you will need to change this code and add error handling ( sample ):

private Task ConnectAsync(DataFeed feed)
{
    var tcs = new TaskCompletionSource<object>();
    feed.OnConnected += _ => tcs.TrySetResult(null);
    feed.BeginConnect();
    return tcs.Task;
}

private Task LoginAsync(DataFeed feed, string user, string password)
{
    var tcs = new TaskCompletionSource<object>();
    feed.OnReady += _ => tcs.TrySetResult(null);
    feed.BeginLogin(user, pass);
    return tcs.Task;
}

Now you can use the following methods:

public async void InitConnection()
{
    var feed = new DataFeed(host, port);
    await ConnectAsync(feed);
    await LoadAsync(feed, user, pass);
    //Now I'm ready
}

. DataFeed. DataFeed, TaskFactory.FromAsync APM API .

, TaskCompletionSource, Task, Task<object>.

+9

DataFeed . . , DataFeed Task ( Task<T>), ConnectAsync ().

, Socket, , XXXAsync Socket ! - TcpClient TcpListener ( 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);
}

:

await client.ConnectAsync(...);

if (!(await LoginAsync(client, ...))) throw new UnauthorizedException(...);

// We're logged in

, , TCP- . , await . , - -.

, Socket, , , Task.FromAsync, BeginXXX/EndXXX - .

0

Source: https://habr.com/ru/post/1544284/


All Articles