如何设置超时值线c#code的 [英] How to set timeout for a line of c# code

查看:78
本文介绍了如何设置超时值线c#code的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  超时设置为操作

如何设置超时在C#线code的。
例如
RunThisLine(的someMethod(一些输入),TimeSpan.FromSeconds(10))
运行的someMethod 10秒到时。
先谢谢了。

How can i set timeout for a line of code in c#. For example RunThisLine(SomeMethod(Some Input), TimeSpan.FromSeconds(10)) run SomeMethod with 10 second time out. Thanks in advance.

推荐答案

您可以使用任务并行库。更确切的说,你可以使用<一个href=\"https://msdn.microsoft.com/en-us/library/dd235606(v=vs.110).aspx\"><$c$c>Task.Wait(TimeSpan):

You can use the Task Parallel Library. To be more exact, you can use Task.Wait(TimeSpan):

using System.Threading.Tasks;

var task = Task.Run(() => SomeMethod(input));
if (task.Wait(TimeSpan.FromSeconds(10)))
    return task.Result;
else
    throw new Exception("Timed out");

这篇关于如何设置超时值线c#code的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆