如何解决C#最佳实践,将独立的任务与等待的任务一起运行
应用程序: Asp.Net Core Web API
我有要求,收到通知后,我应该执行2个独立的任务。通知作为Web钩子的一部分被触发。
- 调用另一个服务,然后将响应保存在日志中。 由于这是独立的任务,因此我不想等到调用者,直到我们收到响应。所以我想将此函数包装在Task.Run()中,以便它将在线程池上可用的另一个线程上运行。 我不在乎它失败还是成功,我只需要记录响应即可。
Task.Run(() => ProcessthroughRestClient(this.httpContext.Request,this.cspgConfiguration.Value.ApacNotificationService,this.restClient,this.logger));
await this.invoiceDbInstance.UpdateItemAsync(payment);
下面是完整代码。
主要方法
public async Task<IActionResult> NotifyAsync()
{
this.logger.LogTrace("{CorrelationId} - notify async method has been called.",this.CorrelationId);
Task.Run(() => ProcessthroughRestClient(this.httpContext.Request,this.Configuration.Value.NotificationService,this.logger));
var request = this.GetdatafeedRequest(this.httpContext.Request);
if (request != null)
{
this.logger.Loginformation("{CorrelationId} - data Feed invoked with the order reference {OrderReference}",request.OrderReference,this.CorrelationId);
Func<Invoice,bool> condition = x => x.sourceTransactionId == request.OrderReference;
var payment = this.invoiceDbInstance.GetItem(condition);
if (payment != null)
{
payment.TransactionStatus = request.IsSuccessstatusCode() ? TransactionStatus.Success : TransactionStatus.Failure;
payment.TransactionId = request.PaymentReference;
payment.UpdatedAt = DateTime.UtcNow.ToLongDateString();
await this.invoiceDbInstance.UpdateItemAsync(payment);
this.logger.Loginformation("{CorrelationId} - data Feed updated order reference {OrderReference} updated in Invoice with {PaymentReference}",this.CorrelationId,request.PaymentReference);
}
else
{
this.logger.Loginformation("{CorrelationId} - Payment not found.",this.CorrelationId);
}
}
this.logger.LogTrace("{CorrelationId}- notify async method ended.",this.CorrelationId);
return new OkResult();
}
将通过Task.Run()
调用的Http调用函数private static HttpResponseMessage ProcessthroughRestClient(HttpRequest request,string url,IRestClient client,ILogger<PayDollarNotificationService> log)
{
try
{
log.LogTrace("Paydollar notify async ProcessthroughRestClient method has been called.");
var parameters = request.Form?.ToDictionary(x => x.Key,x => x.Value.ToString());
if (parameters.Any())
{
var response = client.PostAsync(url,RestClientHelper.BuildFormUrlEncodedContent(parameters)).Result;
log.Loginformation("sent request to {url}.",url);
log.Loginformation($"{url} response {response.ReadContent()?.Result}");
return response;
}
else
{
log.Loginformation("No form parameters found.");
return null;
}
}
catch (Exception ex)
{
log.LogError($"An error occured: {ex.Message} {ex}");
}
return null;
}
我的问题是,使用上面的Task.Run()代替可诱使的任务有什么好处吗?还是会阻塞线程?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。