如何创建一个新线程来执行Action <T>

seb*_*mez 8 .net c# multithreading action

标题几乎都说明了.我有一些方法需要在一个新线程上运行,因为创建线程之前的所有代码几乎相同,我想我会创建一个函数,可以将我需要调用的Action作为参数.

问题是,我还没有找到如何告诉线程它需要执行Action.这甚至可能吗?这是我正在尝试做的一些示例代码.

private void ExecuteInBiggerStackThread(Action<Helper> action, Parameters parms)
{
    ParameterizedThreadStart operation = new ParameterizedThreadStart(action);// here's the mess
    Thread bigStackThread = new Thread(operation, 1024 * 1024);

    bigStackThread.Start(parms);
    bigStackThread.Join();
}
Run Code Online (Sandbox Code Playgroud)

问候,
seba

Tob*_*oby 8

我甚至都不打扰ParameterizedThreadStart.让编译器完成脏工作:

private void ExecuteInBiggerStackThread(Action<Helper> action, Helper h)
{
    Thread bigStackThread = new Thread(() => action(h), 1024 * 1024);

    bigStackThread.Start();
    bigStackThread.Join();
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以更进一步,将签名更改为:

private void ExecuteInBiggerStackThread(Action action) { ... }
Run Code Online (Sandbox Code Playgroud)


Mar*_*ann 7

像这样的东西应该做的伎俩:

private void ExecuteInBiggerStackThread(Action<Helper> action, Helper h)
{
    var operation = new ParameterizedThreadStart(obj => action((Helper)obj));
    Thread bigStackThread = new Thread(operation, 1024 * 1024);

    bigStackThread.Start(h);
    bigStackThread.Join();
}
Run Code Online (Sandbox Code Playgroud)