Question

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>
Was it helpful?

OTHER TIPS

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:

T DoLengthyOperation<T>(int TimeoutInMilliseconds, Func<T> operation)

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.

Instead of mixing out and bool I would instead construct a separate type to capture the return. For example

struct Result<T> {
  private bool _isSuccess;
  private T _value;
  public bool IsSucces { get { return _success; } }
  public T Value { get { return _value; } }
  public Result(T value) {
    _value = value;
    _isSuccess = true;
  }
}

This 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

  1. Move the long running operation onto another thread.
  2. Add cancellation support to the long running operation and signal cancellation from another thread.
  3. Ingrain the notion of timeout into the operation itself and have it check for the time being expired at many points in the operation.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top