添加“超时” “Func”的参数在 C# 4.0 中
使用 C# 4.0 功能,我需要一个通用包装器来封装函数并向其添加 TimeOut 参数。
例如,我们有一个如下函数:
T DoLengthyOperation()
使用 Func
我们有:
Func<T>
这很好,甚至可以调用该函数 Sync
(Invloke
) 或 异步(
BeginInvoke
)。 现在考虑将 TimeOut
添加到此行为中,如果 DoLengthyOperation()
在指定时间内返回,我们将返回 true
,否则 假
。
像这样的东西:
FuncTimeOut<in T1, in T2, ..., out TResult, int timeOut, bool result>
Using C# 4.0
features I want a generic wrapper for encapsulating functions and add a TimeOut
parameter to them.
For example we have a function like:
T DoLengthyOperation()
Using Func
we have:
Func<T>
This is good and call the function even Sync
(Invloke
) or Async
(BeginInvoke
).
Now think of a TimeOut
to be added to this behavior and if DoLengthyOperation()
returns in specified time we have true
returned, otherwise false
.
Something like:
FuncTimeOut<in T1, in T2, ..., out TResult, int timeOut, bool result>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实现 C# 通用超时
Implement C# Generic Timeout
不要返回 true/false 来完成。抛出异常。
我没有时间实现它,但应该是可能的,并且您的基本签名如下所示:
您可以通过传入任何 Func的名称来调用此方法。作为参数或将其定义为 lambda 表达式。不幸的是,您还需要为所需的不同类型的函数提供重载,因为目前无法指定变量号和泛型类型参数。
Don't return true/false for complete. Throw an exception.
I don't have time to implement it, but it should be possible and your basic signature would look like this:
And you could call this method either by passing in the name of any Func<T> as an argument or define it place as a lambda expression. Unfortunately, you'll also need to provide an overload for different kind of function you want, as there's currently no way to specify a variable number a generic type arguments.
我不会混合
out
和bool
,而是构造一个单独的类型来捕获返回。例如这肯定是可以写的。唯一的问题是,为了实现超时,有必要执行以下操作之一:
很难确定哪一个最适合您,因为我们对您的情况了解不够。但我的直觉是选择#2 或#3。让主代码不必切换线程可能是对代码影响最小的更改。
Instead of mixing
out
andbool
I would instead construct a separate type to capture the return. For exampleThis is definitely possible to write. The only problem is that in order to implement a timeout, it's necessary to do one of the following
Which is best for you is hard to determine because we don't know enough about your scenario. My instinct though would be to go for #2 or #3. Having the primary code not have to switch threads is likely the least impactful change to your code.