-1

I know there are a lot of alternatives out there where we can pass a Func through the parameter and call it from inside the body method.

My issue expands on this a little more. I have a DataTable with a ReaderWriterLock and want to centralize where I am doing the locking. My idea is to have a method that accepts a lambda, and from there I can do something like this.

public void processLambda(some lambda/callback param) {
    readWriteLock.acquireWriteLock(-1);
    try {
        // execute method here, which may write to the datatable.
    } finally {
        readWriteLock.releaseWriteLock();
    }
}

How should I go about this? I do not know ahead of time what type of parameters this method will have.

Jacob Macallan
  • 959
  • 2
  • 8
  • 29

2 Answers2

0

One option is for your method to accept an Action (no parameters), and then, if there are parameters, to insert them using a lambda.

public void processLambda(Action baseMethod) {
    readWriteLock.acquireWriteLock(-1);
    try {
        baseMethod.Invoke();
    } finally {
        readWriteLock.releaseWriteLock();
    }
}

public void Main()
{
   processLambda(parameterlessMethod);
   processLambda(() => methodWithParameters(param1, param2, ...)); 
}
user6456942
  • 11
  • 1
  • 1
0

You can use the Delegate type, which can refer to any delegate.

 public void InvokeWriteMethod(Delegate method, params object[] args)
 {
     readWriteLock.AcquireWriterLock(-1);

     try
     {
         method.DynamicInvoke(args);
     }
     finally
     {
         readWriteLock.ReleaseWriterLock();
     }
 }

You can then call it by passing a delegate of any type and either an object array of arguments for the delegated method or zero, one or more discrete arguments:

InvokeWriteMethod(SomeMethod);
InvokeWriteMethod(SomeOtherMethod, new object[] {val1, val2, val3});
InvokeWriteMethod(YetAnotherMethod, val4, val5, val6);
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46