The title pretty much says it. I have some methods that need to run on a new thread and since all the code before creating the thread is pretty much the same, I thought I would create a function that could take as a parameter the Action I need to invoke.
Problem is, I have not found how to tell the thread that it needs to execute the Action. Is that even possible? Here's a little sample code of what I'm trying to do.
private void ExecuteInBiggerStackThread(Action<H开发者_如何学Goelper> action, Parameters parms)
{
ParameterizedThreadStart operation = new ParameterizedThreadStart(action);// here's the mess
Thread bigStackThread = new Thread(operation, 1024 * 1024);
bigStackThread.Start(parms);
bigStackThread.Join();
}
Regards,
sebaI wouldn't even bother with ParameterizedThreadStart
. Let the compiler do the dirty work:
private void ExecuteInBiggerStackThread(Action<Helper> action, Helper h)
{
Thread bigStackThread = new Thread(() => action(h), 1024 * 1024);
bigStackThread.Start();
bigStackThread.Join();
}
Of course, you could carry this a step further and change the signature to:
private void ExecuteInBiggerStackThread(Action action) { ... }
Something like this ought to do the trick:
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();
}
Or a more generic version of the method....
protected void ExecuteInBiggerStackThread<T>(Action<T> action, T parameterObject)
{
var bigStackThread = new Thread(() => action(parameterObject), 1024 * 1024);
bigStackThread.Start();
bigStackThread.Join();
}
Try using Action<object>
and then cast to Helper
in the Action's body
精彩评论