【发布时间】:2019-06-03 04:21:34
【问题描述】:
我有一个 .NET Core 2.2 Web Api 项目,我正在尝试使用 async/await 方法完成所有工作。我有一个名为“UserController”的控制器。我的“UserController”中有需要访问 LoggedInUserId 的方法。因此,为了实现这一点,我创建了一个“UserController”将从中继承的“BaseController”。
BaseController.cs
public abstract class BaseController : ControllerBase
{
public int LoggedInUserId
{
get
{
Task<int> task = Task.Run(async () => await GetLoggedInUserId());
return task.Result;
}
}
}
“BaseController”中有一个名为“GetLoggedInUserId()”的私有方法,它将调用数据库(这就是该方法需要异步的原因)并检索我需要的信息。
所以,了解之后,这里是我的“UserController”
UserController.cs
[Route("api/[controller]")]
[ApiController]
public class UsersController : BaseController
{
public UsersController()
{
}
[HttpPost("create")]
public async Task<ActionResult<User>> Create([FromBody] userCreate)
{
_userService.CreateUser(userCreate, LoggedInUserId);
}
}
如您所见,我正在从“BaseController”访问“LoggedInUserId”属性,但我担心的是因为“BaseController”中的“LoggedInUserId”属性返回一个“task.Result”,它不是真正的异步.
所以,我想到了另一种方法,那就是从“BaseController”中删除“LoggedInUserId”属性,并使“GetLoggedInUserId()”方法成为公共方法而不是私有方法,并按如下方式访问它:
UserController.cs
_userService.CreateUser(userCreate, await GetLoggedInUserId());
所以我的问题如下:
- 这两种方法是否都被认为是正确的,它们是否都符合 async/await 的处理方式?
- 这两种方法能完成同样的事情吗?
- 这两种方法中的任何一种都有它们的缺点吗?
- 如果有人发现这些方法有任何错误,您能否提出一种更好/更清洁的方法来实现我的目标。
【问题讨论】:
标签: c# asp.net-core .net-core async-await