如何超时此任务

How to timout on this task

我正在调用第三方库API的运行方法如下

await Task.Factory.StartNew(() => ThirdPartLibraryAPI.Run());

我想为此设置一些超时,以防 API 花费太长时间。我该怎么做?

您可以使用此代码段

Task t = Task.Factory.StartNew(() => ThirdPartLibraryAPI.Run());
Task.WaitAny(t, miliseconds);

这是一个代码片段:

        var timeoutTask = Task.Delay(1500);
        //using .ContinueWith(t => /*stuff to do on timeout*/);
        //will cause the code to execute even if the timeout did not happen.
        //remember that this task keeps running. we are just not waiting for it
        //in case the worker task finishes first.

        var workerTask = Task.Run(() => { ThirdPartLibraryAPI.Run() });
        var taskThatCompletedFirst = await Task.WhenAny(timeoutTask, workerTask);

        //stuff to do on timeout can be done here
        //if (taskThatCompletedFirst == timeoutTask)