多线程在c#精简框架
问题描述:
我正在使用紧凑框架工作为我的Windows移动应用程序,其中我已经传递多个请求到服务器和接收数组中的每个请求的响应。多线程在c#精简框架
问题出在我应该访问这些数组时,因为我在for循环中启动线程,完成循环后我必须访问这些数组。
I M很迷糊中,我怎么知道,所有线程都完成,使我对这些阵列
帮助需要尽快开始处理。请。
答
如何:
private readonly object syncRoot = new object();
private object[] responses;
public void StartThreads(int numberOfThreads)
{
this.responses = new object[numberOfThreads];
List<Thread> threads = new List<Thread>();
for (int i = 0; i < numberOfThreads; ++i)
{
Thread thread = new Thread(this.DoWork);
thread.Name = i.ToString();
threads.Add(thread);
thread.Start();
}
foreach (Thread thread in threads)
{
thread.Join();
}
// all threads are done.
}
private void DoWork()
{
// do web call
// object response = web.GetResponse();
int threadNumber = Convert.ToInt32(Thread.CurrentThread.Name);
lock (this.syncRoot)
{
this.responses[threadNumber] = response;
}
}
答
//Declare this in class
public delegate void delege();
//Write this lines when you want to background thread start
Thread thread = new Thread(new ThreadStart(() => {
//Do what you what with backgorund threading , can not use any interface comand here
BeginInvoke(new delege(() => {
//Do here any main thread thread job,this can do interface and control jobs without any error
}));
}));
thread.Start();
为什么不直接使用一个线程发送请求,并对其进行处理从队列? – 2009-10-10 04:36:27