这些总是有趣的问题来思考,当然有多种方法来解决它。
对我来说很好的一种方法是提供一个回调方法,每个线程都使用回调方法来返回结果和状态。在下面的示例中,我使用List来跟踪正在运行的线程并将结果放入Dictionary中。
using System; using System.Collections.Generic; 使用System.Linq的; 使用System.Text;使用System.Threading的 ;使用System.Timers的 ;
命名空间ConsoleApplication1 { 类节目 { 静态字典threadResults =新词典(); static int threadMax = 2;
static void Main(string[] args)
{
List<Thread> runningThreads = new List<Thread>();
for (int i = 0; i < threadMax; i++)
{
Worker worker = new Worker();
worker.Callback = new Worker.CallbackDelegate(ThreadDone);
Thread workerThread = new Thread(worker.DoSomething);
workerThread.IsBackground = true;
runningThreads.Add(workerThread);
workerThread.Start();
}
foreach (Thread thread in runningThreads) thread.Join();
}
public static void ThreadDone(int threadIdArg, object resultsArg)
{
threadResults[threadIdArg] = resultsArg;
}
}
class Worker
{
public delegate void CallbackDelegate(int threadIdArg, object resultArg);
public CallbackDelegate Callback { get; set; }
public void DoSomething()
{
// do your thing and put it into results
object results = new object();
int myThreadId = Thread.CurrentThread.ManagedThreadId;
Callback(myThreadId, results);
}
}
}
我也喜欢这个。我希望社区能帮助我找出最好的方法 – MedicineMan 2009-08-26 17:27:53
出于好奇,是否有一个原因为什么你选择背景初始化?从我所看到的情况来看,现在您将拥有两个后台线程的开销,而主线程处于空闲状态并等待它们完成。 – 2009-08-26 17:30:32
@Jesse Squire:这只是一个例子。据我所知,真正的应用程序可能有N个资源,其中N> 2。主线程在执行'Join'之前可能有其他想做的事情。 – 2009-08-26 17:54:19