We have an ASP.Net MVC application for our online store. User has to choose from multiple payment methods in order to buy something. For this we have implemented an abstract factory pattern:
public interface IPaymentServiceFactory
{
IPaymentService GetPaymentService(PaymentServiceEnum paymentServiceType);
}
public interface IPaymentService
{
PaymentSettingsModel GetPaymentSettingsModel();
}
It is used in our Action:
public ActionResult ProcessCart(PaymentDataModel paymentData)
{
var paymentService = _paymentServiceFactory.GetPaymentService(paymentData.PaymentServiceType);
var paymentSettings = paymentService.GetPaymentSettingsModel();
}
The problem occurs when we understand that some payment methods require async calls inside. For example 3rd party online payment service method must be asynchronously called through http for creating payment object on their side. The implemetation:
public class OnlinePaymentService : IPaymentService
{
private readonly IOnlinePaymentServiceApiClient _client;
public async Task<PaymentSettingsModel> GetPaymentSettings()
{
var result = await _client.CreatePaymentAsync();
return result;
}
}
So we come up with a question: How to handle async and sync scenario for different payment methods. We`v decided to make everything async. Updated code:
public interface IPaymentService
{
Task<PaymentSettingsModel> GetPaymentSettings();
}
public async Task<ActionResult> ProcessCart(PaymentDataModel paymentData)
{
var paymentService = _paymentServiceFactory.GetPaymentService(paymentData.PaymentServiceType);
var paymentSettings = await paymentService.GetPaymentSettingsModel();
}
So far so good, but for implementing this for all other payment methods we were forced to use Task.Run:
public class CashPaymentService : IPaymentService
{
public async Task<PaymentSettingsModel> GetPaymentSettings()
{
return await Task.Run(() => new PaymentSettingsModel());;
}
}
As i can understand this creates two different threads for processing Action, which can cause performance issue. Is there way to avoid such consequences? Is it really so bad to use Task.Run in particular case?
Aucun commentaire:
Enregistrer un commentaire