(读给底部的关键点!)
好吧,你已经在使用匿名方法。您可以继续使用C#2.0和使代码稍短这样的:
public static void ExecuteMethod1InThread(string msg)
{
Thread t = new Thread(delegate() { log(msg); });
t.IsBackground = true;
t.Start();
t.Join();
}
或者你可以使用从C#3 lambda表达式:
public static void ExecuteMethod1InThread(string msg)
{
Thread t = new Thread(() => log(msg));
t.IsBackground = true;
t.Start();
t.Join();
}
现在你可以让这个简单的调用不同的方法像这样:
public static void ExecuteMethodInThread<T>(Action<T> method, T argument)
{
Thread t = new Thread(() => method(argument));
t.IsBackground = true;
t.Start();
t.Join();
}
你会再与称之为:
ExecuteMethodInThread(Log, "message");
ExecuteMethodInThread(DifferentMethod, 10);
(例如)。
或者,你可以改变它只是需要一个ThreadStart入手:
public static void ExecuteMethodInThread(ThreadStart action)
{
Thread t = new Thread(action);
t.IsBackground = true;
t.Start();
t.Join();
}
,并调用它像这样:
这不是相当等同,但是,由于何时评估各种表达式。特别是,在循环中执行此操作可能会导致问题Eric Lippert describes here。
重要的一点
然而,目前你有什么会伤害性能。你开始一个新的线程(而不是使用线程池),然后你等待线程完成。这是有效同步调用log
方法 - 如何可以帮助性能?
这是性能比使用配发更糟反射。创建一个线程来调用一个方法是一个不错的选择。你应该使用线程池。 – 2010-02-10 11:15:55