简体   繁体   English

如何对这项任务进行调整

[英]How to timout on this task

I am calling a third party library API's Run method as follows 我正在按如下方式调用第三方库API的Run方法

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

I would like to setup some timeout on this in case this API takes too long. 我想为此设置一些超时,以防此API花费太长时间。 How can I do that? 我怎样才能做到这一点?

Here is a code snippet: 这是一个代码片段:

        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)

you can use this snippet 您可以使用此片段

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM