How to pass a method as a parameter to another method using linq expressions

I want to create a method that runs another method in a background thread. Something like that:

void Method1(string param)
{
    // Some Code
}

void Method2(string param)
{
    // Some Code
}

void RunInThread(AMethod m)
{
   //Run the method in a background thread
}
+5
source share
2 answers

If your method has a return value, use the Func delegate, otherwise you can use the Delegate . eg:

void Method1(string param)
{
    // Some Code
}

void Method2(string param)
{
   // Some Code
}

void RunInThread(Action<string> m)
{
   //Run the method in a background thread
}

Then you can call RunInThreadas follows:

RunInThread(Method1);
RunInThread(Method2);
+8
source

I like it Task.Runwhen I just want some code to run in the background thread. It looks like it has almost the same signature as what you are trying to identify. Many other overloads too.

Task.Run(()=>{ 
      //background method code 
   }, TResult);

MSDN Documentation

+2
source

All Articles