【问题标题】:How do I pass a method as the parameter of another method using linq expressions如何使用 linq 表达式将方法作为另一个方法的参数传递
【发布时间】:2013-04-01 17:22:59
【问题描述】:

我想创建一个在后台线程中运行另一个方法的方法。像这样的:

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

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

void RunInThread(AMethod m)
{
   //Run the method in a background thread
}

【问题讨论】:

标签: c# linq expression func


【解决方案1】:

如果您的方法有返回值,请使用Func 委托,否则您可以使用Action 委托。例如:

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

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

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

那你可以这样拨打RunInThread

RunInThread(Method1);
RunInThread(Method2);

【讨论】:

  • 您可以添加 2 种方式在单独的线程中运行它:m.BeginInvoke("Hello", null, null);Task.Factory.StartNew(() =&gt; m("Hello"));
【解决方案2】:

我喜欢Task.Run 当我只想在后台线程中运行一点代码时。它甚至看起来与您要定义的签名几乎相同。还有很多其他的重载。

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

MSDN documentation

【讨论】:

    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    相关资源
    最近更新 更多