【发布时间】:2020-11-09 19:30:09
【问题描述】:
我知道这个问题已经被问过很多次关于堆栈溢出的问题,但我正在寻找一些关于我下面代码的建议。
在我的应用程序中有许多难以修改的同步方法。我无法将所有内容更改为异步等待。但我想异步运行几个方法。
我为此写了一些代码。我还添加了有助于理解我的要求的 cmets。
这是我的代码:
//This class will perform some heavy operation and also going to call an API for tax configuration.
//The original class takes almost 2 sec to respond. Obviously we are refactoring it but also want this class methods to run async way
public static class TaxCalculatorHelper
{
public static Task<double> CalculateTaxAsync(double salary)
{
// I will do some heavy tax calculation here, so I want it to run asynchronously
return Task.FromResult(500.00); // currently returning temporary value
}
}
//The exisiting classes
public class Employee
{
//This method is not going to be async but What I want that Tax calculation which is heavy task that should run asynchronously
public double GetEmployeeFinalSalary(double salary)
{
var taxValue = Task.Run(async () => await TaxCalculatorHelper.CalculateTaxAsync(salary));
//I was doing this
// return taxValue.Result; // I cannot use this because it blocks the calling thread until the asynchronous operation is complete
//Is the below approach correct ?
return taxValue.GetAwaiter().GetResult();
}
}
public class SomeOtherClass
{
private readonly Employee _employee;
public SomeOtherClass()
{
_employee = new Employee();
}
//This will not be async
public void GetEmployeeCtc(double salary)
{
var finalCtc = _employee.GetEmployeeFinalSalary(salary);
}
}
任何人都可以评论并建议我最好的方法吗?
谢谢!!
【问题讨论】:
-
如果您的操作是“真正”异步的,或者在完成某些工作时继续在您的方法中执行某些操作,则通常运行异步操作以节省资源(因此线程可以用于其他一些工作)在平行下。在这种情况下,这两者都不会实现。如果您希望
GetEmployeeFinalSalary不阻塞调用线程,则需要使其异步或返回任务(以便调用者决定如何处理它)。
标签: c# .net .net-core async-await c#-8.0