Pphoenix Pphoenix - 1 year ago 56
C# Question

Cannot await on async method

I am creating a Xamarin application with a shared core. In the shared core I have a connection class for socket communication:

public class ConstantConnection {
public async Task Connect()
{
await conn.Connect (); // Calls a socket plugin to connect
timer = new Timer (new Action<object> (ParseData), "", 100, 1, false); // starts a local timer
}

public async Task Disconnect()
{
timer.Dispose (); // End timer
await conn.Disconnect (); // Close socket
}
}


Now I have another class, working like a constructor, that would like to use objects of the above class by executing:

conn = new ConstantConnection();
await conn.Connect();


This gives me an error in Xamarin Studio which says:


The 'await' operator can only be used within an async method


As far I as I can see
Connect
is
async
. Why can't I use
await
?

Answer Source

Awaiting an async method can only be done in an async method. So you have to create a async method, and then await Connect():

public async void SomeAsync()
{
    await conn.Connect();
}

Else, if you want to run that code in a synchronous method (one not having the async keyword), you should call Wait in order to wait until that method has finished:

conn.Connect().Wait();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download