英文:
Creating a method calling an async method, but the calling method isn't async itself, though returning a Task, but how does it work?
问题
这是你要翻译的内容:
1 - 这是他首先创建的异步方法
public async Task SaveData<T>(
string storedProcedureName,
T parameters,
string connectionString = "Default")
{
using IDbConnection connection = new SqlConnection(_config.GetConnectionString(connectionString));
await connection.ExecuteAsync(
storedProcedureName,
parameters,
commandType: CommandType.StoredProcedure);
}
2 - 这是调用上述方法的方法,没有使用async关键字
public Task InsertUser(UserModel user) =>
_db.SaveData(storedProcedureName: "dbo.spUser_Insert", new { user.FirstName, user.LastName });
我不明白为什么在 InsertUser
方法中不需要使用 async/await
关键字,尽管知道应该等待 Task
才能正确使用它?
英文:
I've watched a video of a person creating a non async method that calls an async method but doesn't use the async/await keywords to do so, and I'm confused.
Here's the code:
1 - This is the async method he created first
public async Task SaveData<T>(
string storedProcedureName,
T parameters,
string connectionString = "Default")
{
using IDbConnection connection = new SqlConnection(_config.GetConnectionString(connectionString));
await connection.ExecuteAsync(
storedProcedureName,
parameters,
commandType: CommandType.StoredProcedure);
}
2 - This is the method calling the above method, without being async
public Task InsertUser(UserModel user) =>
_db.SaveData(storedProcedureName: "dbo.spUser_Insert", new { user.FirstName, user.LastName });
I don't understand how you don't need to have the async/await keywords there for the InsertUser
method knowing that a Task
should be awaited in order to be used right ?
答案1
得分: 2
你需要在方法前声明async
,如果你想在该方法内部使用await
。你的SaveData
方法返回一个Task
。如果你想在调用它时使用await
,那么你只能在一个被声明为async
的方法中这样做。await
会等待返回的Task
完成,然后解封它。你的InsertUser
方法没有使用await
,所以它不需要是async
。它将立即返回Task
,而不会等待它完成。这意味着可以在调用栈的下方进一步等待该Task
,或者如果没有必要知道它何时完成,可以让它并行进行并忽略它。
英文:
You need to declare a method async
if you want to use await
within that method. Your SaveData
method returns a Task
. If you want to await
that method when you call it then you can only do so in a method declared async
. await
will wait until the returned Task
completes and then unwrap it. Your InsertUser
method is not using await
so it doesn't need to be async
. It will just return the Task
immediately and not wait for it to complete. That means that that Task
can be waited on further down the call stack or it can just be allowed to carry on in parallel and ignored if there's no need to know when it completes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论