Function with code as parameter

I have many functions, but I need to run them inside another function.

I know I can do something like this

public void Method1()
{
bla bla
}


public void Method2()
{
bla bla
}

public void Wrapper(Action<string> myMethod)
        {
        method{
            myMethod()
              }
            bla bla
         }

      

And then call them using something like this:

wrapper(Method1());

      

The problem is that sometimes I need to run Method1 and Method2 at the same time. A lot of them. Sometimes one, sometimes several at the same time.

So I think it would be great to do something like this:

Wrapper({bla bla bla; method(); bla bla; }
{
method{
bla bla bla;
 method();
 bla bla;

        }
}

      

Run the code block inside the method and the method parameter is the code block. Do you think this is possible or would you recommend a different approach?

+3


source to share


2 answers


Having

public static void Wrapper(Action<string> myMethod)
{
    //...
}

      

you can specify myMethod

using a lambda expression :

static void Main(string[] args)
{
    Wrapper((s) =>
    {
        //actually whatever here
        int a;
        bool b;
        //..
        Method1();
        Method2();
        //and so on
    });
}

      



That is, you don't need to explicitly define a method with the desired signature (the appropriate here Action<string>

), but you can write an inline lambda expression, doing whatever you need to do.

From MSDN:

Using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls.

+3


source


If you already have a method that takes an Action parameter, you can simply use an anonymous method to group a collection of methods for sequential execution.

//what you have
public void RunThatAction(Action TheAction)
{
  TheAction()
}

//how you call it
Action doManyThings = () =>
{
  DoThatThing();
  DoThatOtherThing();
}
RunThatAction(doManyThings);

      


If calling methods sequentially is something you do often, consider creating a function that takes as many actions as you ...



public void RunTheseActions(params Action[] TheActions)
{
  foreach(Action theAction in TheActions)
  {
    theAction();
  }
}

//called by
RunTheseActions(ThisAction, ThatAction, TheOtherAction);

      


You said "at the same time" twice, which makes me think of parallelism. If you want to run many methods at the same time, you can use Tasks to do this.

public void RunTheseActionsInParallel(params Action[] TheActions)
{
  List<Task> myTasks = new List<Task>(TheActions.Count);
  foreach(Action theAction in TheActions)
  {
    Task newTask = Task.Run(theAction);
    myTasks.Add(newTask);
  }
  foreach(Task theTask in myTasks)
  {
    theTask.Wait();
  }
}

      

+2


source







All Articles