如何在另一个 class 中调用异步任务 <List<>> class?

How to call async Task<List<>> class in another class?

我有这个方法

public async Task<List<InvoiceVAT>> Import(IFormFile file)
{
    var list = new List<InvoiceVAT>();
    using (var stream = new MemoryStream())
    {
        await file.CopyToAsync(stream);
        using (var package = new ExcelPackage(stream))
        {
        }
    }
    return list;
}

但是在尝试调用它时收到以下错误:

There is no argument given that corresponds to the required formal parameter

还有一个警告:

Because this call is not awaited, execution of the current method continuous before the call is completed

我哪里错了?

第一个错误“没有给定的参数对应于所需的形式参数”,意味着您没有提供 Import() 方法所需的 IFormFile 参数。

第二个,“因为没有等待这个调用,在调用完成之前继续执行当前方法。”,因为 Import() 被定义为异步方法并且应该调用它等待。 这意味着调用方方法也是异步的,其中 Import() 应该这样调用:

IFormFile formFile; //Assuming formFile is initiated or provided.
var invoiceVATs = await Import(formFile); //Assuming this is an instance method within the same class as Import()

或者需要同步获取异步方法的Result(阻塞调用方方法,等待异步方法完成),不推荐的做法:

IFormFile formFile; //Assuming formFile is initiated or provided.
var invoiceVATs = Import(formFile).Result; //Assuming this is an instance method within the same class as Import()

如果您想了解更多关于异步编程的信息,这里是一个很棒的material:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/