我正在尝试从 Azure 函数调用 face api 异步方法。我正在等待异步方法,但 Azure 函数关闭并完成它。如何在 Azure 功能中等待异步操作完成?
这是我的代码(我使用的是 VS 2017,.Net 标准 2.0):
public static class IdentifyHttp
{
[FunctionName("IdentifyHttp")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
string url = new StreamReader(req.Body).ReadToEnd();
//string url = req.Query["url"];
Stream rtn = null;
HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse aResponse = (HttpWebResponse)aRequest.GetResponse();
StreamReader sReader = new StreamReader(aResponse.GetResponseStream(), System.Text.Encoding.Default);
rtn = sReader.BaseStream;
AnalyzeImageFaceAPIAsync(rtn);
return url != null
? (ActionResult)new OkObjectResult($"Hello, {url}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
private static async void AnalyzeImageFaceAPIAsync(Stream s)
{
string PersonGroupId = "employees";
FaceServiceClient FaceServiceAPIClient = new FaceServiceClient("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "https://eastus.api.cognitive.microsoft.com/face/v1.0");
string name = "No one identified";
//s.Seek(0, SeekOrigin.Begin);
var faces = await FaceServiceAPIClient.DetectAsync(s);
var faceIds = faces.Select(face => face.FaceId).ToArray();
var results = await FaceServiceAPIClient.IdentifyAsync(PersonGroupId, faceIds);
foreach (var identifyResult in results)
{
if (identifyResult.Candidates.Length > 0)
{
var candidateId = identifyResult.Candidates[0].PersonId;
var person = await FaceServiceAPIClient.GetPersonAsync(PersonGroupId, candidateId);
name = person.Name;
}
}
}
}