【发布时间】:2018-10-11 20:17:36
【问题描述】:
我有一个 API 负责在数据库中插入文本消息详细信息。 它通过对存储库进行同步调用来实现,我认为这可以异步实现。我怎样才能实现这一点?或者什么是处理这种情况的最佳方法。代码 sn-p 示例受到高度赞赏,因为我仍然在围绕 .NET 前进。
api:
public IHttpActionResult SendSMSNotification([FromBody] SMSNotification smsNotification)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_service.SendSMS(smsNotification);
return Ok();
}
服务:
internal void SendSMS(SMSNotification smsNotification)
{
_repository.Notify(_mapperService.GetSMSNotification(smsNotification));
}
映射器:
public SMSNotification GetSMSNotification(SMSNotification message)
{
return AutoMapper.Mapper.Map<SMSNotification>(message);
}
回购:
public virtual bool Notify(SMSNotification request)
{
using (var sql = _sqlMapper.CreateCommand('Database', 'Stored proc'))
{
sql.AddParam("@fMessage", request.Message);
//..............
//.............. more params
var retvalParamOutput = sql.AddOutputParam("@fRetVal", System.Data.SqlDbType.Int);
sql.Execute();
return retvalParamOutput.GetSafeValue<int>() == 1;
}
}
这里的sql是一个自定义的东西,它有以下方法:
public static int Execute(this IDataCommand @this);
[AsyncStateMachine(typeof(<ExecuteAsync>d__1))]
public static Task<int> ExecuteAsync(this IDataCommand @this);
【问题讨论】:
-
sql在您的Notify方法中是什么类型? -
如果您使用的 I/O 对象支持异步,则可以将其设为异步。你用的是什么数据库?您使用哪些类与该数据库进行交互。
-
它是一个在现有代码库中使用的自定义类,在本例中为 SQL Server 中的普通 sql 任务提供了便利。
-
有没有办法可以从 Api 异步调用 _service.SendSMS(smsNotification)?
-
或者可以转成Task吗?
标签: c# asp.net .net asp.net-web-api async-await