[英]Async/await simple example
Im trying to understand the basics of async/await by creating a simple example. 我试图通过创建一个简单的例子来理解async / await的基础知识。 Im using Sqlite with an Async connection and I have a class like this:
我使用Sqlite与Async连接,我有一个这样的类:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
Now lets say that I want to save a User
to my UserTable and when the saving is done I wish to retrieve it. 现在让我们说我想将
User
保存到我的UserTable中,当保存完成后我想要检索它。
public async ? SaveToDb()
{
_conn.CreateTableAsync<User>();
await _conn.InsertAsync(new User(){Id=1, Name = "Bill"});
//Code that waits for the save to complete and then retrieves the user
}
I suspect that I need a task somewhere, but im not completely sure how to do this. 我怀疑我需要某个任务,但我不完全确定如何做到这一点。 Thank you
谢谢
You're mostly there already. 你已经在那里了。
When returning void
: 返回
void
:
public async Task SomethingAsync()
{
await DoSomethingAsync();
}
When returning a result: 返回结果时:
public async Task<string> SomethingAsync()
{
return await DoSomethingAsync();
}
The thing to note when returning a value in an async method is that you return the inner type (ie in this case string
) rather than a Task<string>
instance. 在异步方法中返回值时要注意的是返回内部类型(即在本例中为
string
)而不是Task<string>
实例。
If your code doesn't return any value, the signature should be this, returning Task
: 如果您的代码没有返回任何值,则签名应为此,返回
Task
:
public async Task SaveToDb()
Else, you would need to specify the return type as the type argument in Task<T>
, string
in this sample: 否则,您需要在此示例中将
Task<T>
中的string
参数指定为返回类型:
public async Task<string> SaveToDb()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.