简体   繁体   English

从Web API操作方法调用异步方法

[英]Calling an async method from Web API action method

I'm calling an async method from my Web API action method that looks like this but I'm getting "Cannot implicitly convert type Task Employee to Employee" error. 我正在从如下所示的Web API操作方法调用异步方法,但出现“无法将类型Task Employee隐式转换为Employee”错误。

What do I need to do? 我需要做什么?

My Web API action method looks like this: 我的Web API操作方法如下所示:

public IHttpActionResult GetEmployee()
{

   // Get employee info
   Employee emp = myDataMethod.GetSomeEmployee();

   return Ok(emp);
}

And the method I'm calling looks like this: 我正在调用的方法如下所示:

public static async Task<Employee> GetSomeEmployee()
{
   Employee employee = new Employee();

   // Some logic here to retrieve employee info

   return employee;
}

What do I need to do so that I can call this method to retrieve employee information? 我需要怎么做才能调用此方法来检索员工信息?

PS The GetSomeEmployee() method has to be async because it makes other async calls to retrieve employee data. PS GetSomeEmployee()方法必须是异步的,因为它会进行其他异步调用来检索员工数据。

You need to either call the method synchronously, or use await . 您需要同步调用该方法,或者使用await Eg: 例如:

Synchronously ( GetEmployee() will block until GetSomeEmployee() completes): 同步( GetEmployee()将阻塞,直到GetSomeEmployee()完成):

public IHttpActionResult GetEmployee()
{

   // Get employee info
   Employee emp = myDataMethod.GetSomeEmployee().Result;

   return Ok(emp);
}

Asynchronously ( GetEmployee() will return immediately, and then be continued when GetSomeEmployee() completes): 异步( GetEmployee()将立即返回,然后在GetSomeEmployee()完成时继续执行):

public async Task<IHttpActionResult> GetEmployee()
{

   // Get employee info
   Employee emp = await myDataMethod.GetSomeEmployee();

   return Ok(emp);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM