【发布时间】:2015-04-28 20:14:30
【问题描述】:
我正在编写一个自定义报告工具,允许用户创建一些非常广泛的查询。我想为此添加一个超时,这样如果用户创建的东西最终会运行很长时间,整个系统就不会停止。我想出了这个:
public List<List<SimpleDisplayField>> FindReport(int reportId)
{
var report = GetReportById(reportId);
var tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
int timeOut = 20000; // 2 seconds
if (report.BidType == "LOB")
{
var task = Task.Factory.StartNew(() => FindLOBReport(report), token);
if (!task.Wait(timeOut, token))
{
throw new Exception("Report ran for more than 10 seconds.. run again or add more filters.");
}
return task.Result;
}
else
{
var task = Task.Factory.StartNew(() => FindFWOReport(report), token);
if (!task.Wait(timeOut, token))
{
throw new Exception("Report ran for more than 10 seconds.. run again or add more filters.");
}
return task.Result;
}
}
这很好,但我想用 Func 将它重构为类似的东西,这样我就可以将 FindLOBReport 或 FindFWOReport 作为参数传递:
public List<List<SimpleDisplayField>> FindReport(int reportId)
{
var report = GetReportById(reportId);
if (report.BidType == "LOB")
{
return RunReport(FindLOBReport(report));
}
else
{
return RunReport(FindFWOReport(report));
}
}
private List<List<SimpleDisplayField>> RunReport(Func<CustomReport, List<List<SimpleDisplayField>>> method)
{
var tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
int timeOut = 20000; // 2 seconds
var task = Task.Factory.StartNew(() => method, token);
if (!task.Wait(timeOut, token))
{
throw new Exception("Report ran for more than 10 seconds.. run again or add more filters.");
}
return task.Result;
}
但是,task.Result 是一个“Func”返回类型,而我只想让 task.Result 返回我的列表>。有什么办法可以补救吗?
【问题讨论】:
-
FindLOBReport是做什么的?它调用数据库吗?顺便说一句,你没有打电话给method。 -
您的函数采用
CustomReport- 您希望它接收什么参数?FindLOBReport的签名是什么?我怀疑您对为委托转换提供方法组和调用方法之间的区别感到有些困惑。 -
@JonSkeet 您的怀疑很可能是正确的。 FindLOBReport 接受一个 CustomReport 并返回一个 2D 列表。
-
@logan_gabriel:是的,听起来您可能想致电
RunReport(FindLOBReport)- 但RunReport也需要接受report。或者你可以调用RunReport(() => FindLOBReport(report)),把RunReport的参数改成Func<List<List<SimpleDisplayField>>> -
您正在执行一个任务并同步等待它。你真的需要这个任务吗?