Pphoenix Pphoenix - 10 months ago 42
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
. Why can't I use

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download