Microsoft Emotions API,RecognizeInVideoAsync c#

时间:2016-10-18 10:25:45

标签: c# multithreading api microsoft-cognitive emotion

我试图通过在视频中使用识别来使用Microsft Emotions Api,所以我下载了客户端库并尝试使用它,但是当我进行调试时,它只是没有任何异常地走出去,我认为它可能是一个线程prbolem - 它发生在方法中:“recognInVideoAsync”。

我的代码:

public static async void testEmotionApi()
{
    var emotionServiceClient = new EmotionServiceClient("c580db97556e405980212f3ff31ac762");

    VideoEmotionRecognitionOperation videoOperation;
    using (var fs = new FileStream(@"D:\Downloads\testForApp.mp4", FileMode.Open))
    {
        videoOperation = await emotionServiceClient.RecognizeInVideoAsync(fs);
    }

    VideoOperationResult operationResult;
    while (true)
    {
        operationResult = await emotionServiceClient.GetOperationResultAsync(videoOperation);
        if (operationResult.Status == VideoOperationStatus.Succeeded || operationResult.Status == VideoOperationStatus.Failed)
        {
            break;
        }

        Task.Delay(30000).Wait();
    }

    var emotionRecognitionJsonString = operationResult.ToString();
}

1 个答案:

答案 0 :(得分:1)

这就是异步编程在C#中的工作原理。虽然在源代码形式中您似乎只有一个方法,但实际上该方法会分成await个边界的多个部分。换句话说,正如您所编写的那样,testEmotionApi方法在调用RecognizeInVideoAsync后返回。当异步调用完成时,将执行该方法的其余部分,但您无法等待该结果。你可以做的是:

public static async Task<VideoOperationResult> testEmotionApi()
{
    // everything here the same, except...
    return operationResult;
}

public async Task callEmotionTestApi()
{
    VideoOperationResult result = await testEmotionApi();
    ...
}

或者,如果您不希望调用者异步,

public void callEmotionTestApi()
{
   VideoOperationResult result = testEmotionApi().GetAwaiter().GetResult();
   ...
}