Task with async 有什么用?

What is the use of Task with async?

异步方法中不使用Task怎么办?我搜索了很多但能够理解为什么我们使用 Taskasync。请提出一些建议,因为两者都是异步的提前致谢。

asyncTask签名示例:

//Controller with async and task 
public async Task<IActionResult> CreateNewBug([FromBody] BugTrackerRequest bugTrackerRequest)
{
   if (ModelState.IsValid)
   {
        var Request = await _projectDetails.CreateNewBug(bugTrackerRequest);
        if (Request > 0)
        {
           return Ok("Success");
        }
    }

   return StatusCode(500, new { Message = "Something went wrong" });
}

What if i don't use Task in the async method?

嗯,这是设计使然。

如果你想使用 async,你有一组有效的 return 类型*:

  • void
  • Task
  • Task<T>
  • task-like type
  • IAsyncEnumerable<T>
  • IAsyncEnumerator<T>

* 此处省略了 lambda 和匿名方法。

其他都无效。 void 被认为是不好的做法。

例如:

public async int DoIt()

会导致这个错误:

Error CS1983 The return type of an async method must be void, Task, Task, a task-like type, IAsyncEnumerable, or IAsyncEnumerator

此外,async 修饰符本身的作用不大。我相信这是一个普遍的误解。

它不会使您的代码“异步”它是任务的组合,以及 await 关键字,它允许您异步执行任务但随后以后续方式继续 - 那就是async/await 构造的用途是什么。

我强烈建议您阅读先生。 Cleary 关于该主题的博客:

https://blog.stephencleary.com/2012/02/async-and-await.html

正如他所说:

The “async” keyword enables the “await” keyword in that method and changes how method results are handled. That’s all the async keyword does! It does not run this method on a thread pool thread, or do any other kind of magic. The async keyword only enables the await keyword (and manages the method results).


如评论所述:如果你想使用等待,你只需要异步。仅当您需要在异步方法之后执行某些操作时才使用 await。

另外:一个任务可能是异步的,但不是必须的。为了简单起见,让我们在以下示例中假设它们是:

一些例子:

// no async, yet possibly asynchronous.
// Task can be returned directly, it's still asynchronous.
public Task<int> ProcessData()
{
   return _dbContext.SaveChangesAsync();
}
// no async, yet possibly asynchronous.
// returning the task directly
public async Task<int> ProcessData()
{
   var result = await _dbContext.SaveChangesAsync();
   //await needed if you want to continue here after the task is completed.
   if (result < 1)
       throw new ValidationException("should be higher then 1");

   return result;   
}

下面2个例子不加任何东西and/or都是无效的:

// returning the task directly
public Task<int> ProcessData()
{
   //ERROR: missing async keyword
   var result = await _dbContext.SaveChangesAsync(); 
   return result;   
}
// returning the task directly
public async Task<int> ProcessData() //WARNING: missing await keyword
{
   //WARNING: missing await keyword
   return _dbContext.SaveChangesAsync(); 
}