Google 语音转文本 API 超时

Google speech to text API Timeout

我想知道是否有办法在 google 语音转文本 API 通话中设置超时。下面的文档是从 wav 文件获取测试的代码。但是我需要的是能够为此 API 调用设置超时。我不想永远等待 Google API 的回复。最多我想等待 5 秒,如果我没有在 5 秒内得到结果,我想抛出一个错误并继续执行。

static object SyncRecognize(string filePath)
{
    var speech = SpeechClient.Create();
    var response = speech.Recognize(new RecognitionConfig()
    {
        Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
        SampleRateHertz = 16000,
        LanguageCode = "en",
    }, RecognitionAudio.FromFile(filePath));
    foreach (var result in response.Results)
    {
        foreach (var alternative in result.Alternatives)
        {
            Console.WriteLine(alternative.Transcript);
        }
    }
    return 0;
}

How to abort a long running method? 原始代码在这里

线程将 运行 在您设置的时间内终止,您可以将异常处理或记录器放在 if 语句中。 long 运行ning 方法仅用于演示目的。

   class Program
    {
        static void Main(string[] args)
        {

            //Method will keep on printing forever as true is true trying to simulate a long runnning method
            void LongRunningMethod()
            {
                while (true)
                {
                    Console.WriteLine("Test");
                }
            }


            //New thread runs for set amount of time then aborts the operation after the time in this case 1 second.
           void StartThread()
            {
                Thread t = new Thread(LongRunningMethod);
                t.Start();
                if (!t.Join(1000)) // give the operation 1s to complete
                {
                    Console.WriteLine("Aborted");
                    // the thread did not complete on its own, so we will abort it now
                    t.Abort();

                }
            }

            //Calling the start thread method.
            StartThread();

        }
    }