C# 给某个方法设定执行超时时间-2
2024-10-07 01:00:41
var response = RunTaskWithTimeout<ReturnType>(
(Func<ReturnType>)delegate { return SomeMethod(someInput); }, ); /// <summary>
/// Generic method to run a task on a background thread with a specific timeout, if the task fails,
/// notifies a user
/// </summary>
/// <typeparam name="T">Return type of function</typeparam>
/// <param name="TaskAction">Function delegate for task to perform</param>
/// <param name="TimeoutSeconds">Time to allow before task times out</param>
/// <returns></returns>
private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
{
Task<T> backgroundTask; try
{
backgroundTask = Task.Factory.StartNew(TaskAction);
backgroundTask.Wait(new TimeSpan(, , TimeoutSeconds));
}
catch (AggregateException ex)
{
// task failed
var failMessage = ex.Flatten().InnerException.Message);
return default(T);
}
catch (Exception ex)
{
// task failed
var failMessage = ex.Message;
return default(T);
} if (!backgroundTask.IsCompleted)
{
// task timed out
return default(T);
} // task succeeded
return backgroundTask.Result;
}
https://stackoverflow.com/questions/13513650/how-to-set-timeout-for-a-line-of-c-sharp-code
最新文章
- 利用XAG在RAC环境下实现GoldenGate自动Failover
- E:“图片视频”的列表页(taxonomy-cat_media.php)
- LINQ to Entities 不支持 LINQ 表达式节点类型“ArrayIndex”
- 如何查看Git对象
- 20145330《Java程序设计》课程总结
- 9.20 java继承
- codeforces 429E
- poolboy的坑
- C# Web Api 上传文件
- HDU 1561-The more, The Better(树状背包)
- oracle数据同步方案
- 一些有用的webservice
- 实现对properties文件的有序读写
- 缓存的概念(反向代理、CDN)
- Eclipse快捷键 10个最有用的快捷键(转)
- 不同浏览器使用Content-disposition时filename带空格的处理方式不同
- VS中,NUnit适合测试者尽心开发自动化测试,而Unit适合开发者开发单元测试。
- VS2015转VS2008
- PHP简单实现购物车
- Struts2如何搭建?