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
?
The error says it all. The method which has the awaiting code should also be async.
public async void ConnectAsync()
{
conn = new ConstantConnection ();
await conn.Connect ();
}
As others have pointed out, await
can only be used within an async
method. However, you should not use async void
!
Since your calling code is a constructor, you'll have to rethink your approach. I describe a variety of approaches on my blog , of which I prefer the async factory method:
private MyConstructor()
{
conn = new ConstantConnection();
}
public async Task<MyConstructor> CreateAsync()
{
var result = new MyConstructor();
await result.Connect();
}
As a side note, your task-returning methods should be named with an Async
suffix to follow the TAP guidelines . Eg, Connect
should be ConnectAsync
, etc.
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();
I agree with Stephen, async void is called "Fire and Forget", it's can bring a lot of issues to your code.
Always use:
public async Task<"Type"> Example()
{
}
or in "void" case use:
public async Task Example()
{
}
All MVP's recomend this...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.