等待主线程直到其他线程无法完成!

时间:2011-02-28 08:08:41

标签: c# multithreading

我没有使用任何线程池。只是创建ThreadArray.for循环创建线程但同时主线程继续....如何在主线程上应用wait,直到for循环创建的所有线程都没有完成。

代码:

   public List<DirInfo> ScanDir()
        {
     for (int i = 0; i < 5; i++)
            {
                threadArray[i] = new Thread(delegate()
                    {
                       StartScanning(paths);
                    }
                );
                threadArray[i].Start();
            }
....
List<DirInfo> listInfo = new List<DirInfo>();
...
...
....
return listInfo
}

代码:

 public List<ServerDataInformation> ScanParallel()
    {
        var appConfigData = ReadAppConfig();
        if (appConfigData == null)
        {
            EventPublisher.NotifyApplication("Error in appconfig File");
            return null;
        }

        int pathCount = appConfigData.Length;
        string serverPath;
        string serverName;
        var waitHandles = new WaitHandle[pathCount];
        Thread[] threadArray = new Thread[pathCount];

        for (int i = 0; i < pathCount; i++)
        {
            // waitHandles[i] = new AutoResetEvent(false);
            var handle = new EventWaitHandle(false, EventResetMode.ManualReset);
            serverPath = appConfigData[i].Split(',').First();
            serverName = appConfigData[i].Split(',').Last();
            var threadSplit = new Thread(() =>
                 {
                     ScanProcess(serverPath, serverName);  --------->> not executing as many times as I increment
                     handle.Set();
                 });

            waitHandles[i] = handle;
            threadSplit.Start();



        }
        //if (WaitHandle.WaitAll(waitHandles))
        //{
        //    return serverDataInfoList;
        //    // EventPublisher.NotifyApplication("timeout!!");
        //}

        return serverDataInfoList;
    }

这里4是pathCount的长度但是

ScanProcess(serverPath, serverName);

没有使用不同的值执行4次。它正在执行4次但具有相同的vaues

5 个答案:

答案 0 :(得分:8)

您可以使用等待句柄:

var waitHandles = new ManualResetEvent[10];
for (int i = 0; i < 10; i++)
{
    waitHandles[i] = new ManualResetEvent(false);
    new Thread(waitHandle =>
    {
        // TODO: Do some processing...

        // signal the corresponding wait handle
        // ideally wrap the processing in a try/finally
        // to ensure that the handle has been signaled
        (waitHandle as ManualResetEvent).Set();
    }).Start(waitHandles[i]);
}

// wait for all handles to be signaled => this will block the main
// thread until all the handles have been signaled (calling .Set on them)
// which would indicate that the background threads have finished
// We also define a 30s timeout to avoid blocking forever
if (!WaitHandle.WaitAll(waitHandles, TimeSpan.FromSeconds(30)))
{
    // timeout
}

答案 1 :(得分:7)

您是否尝试过.Net 4任务并行库

MSDN Task Parallel Library

Task[] tasks = new Task[3]
{
    Task.Factory.StartNew(() => MethodA()),
    Task.Factory.StartNew(() => MethodB()),
    Task.Factory.StartNew(() => MethodC())
};

//Block until all tasks complete.
Task.WaitAll(tasks);

// Continue on this thread...

答案 2 :(得分:0)

将每个线程与waithandle关联,然后使用WaitHandle.WaitAll。如果通过异步委托调用而不是新的线程对象启动线程,它将为您提供async结果as waithandle。

答案 3 :(得分:0)

   for(int i = 0;i<10;i++)
   {   
     thread = new Thread(new ThreadStart(Get_CR_Information));
         thread.IsBackground = true;
          thread.Start();
        WaitHandle[] AWait = new WaitHandle[] { new AutoResetEvent(false) };
        while ( thread.IsAlive)
        {
            WaitHandle.WaitAny(AWait, 50, false);
            System.Windows.Forms.Application.DoEvents();
        } 
    }

试试这个它会正常工作......

答案 4 :(得分:0)

尝试使用CountdownEvent同步原语,下面的链接包含一个示例。

https://msdn.microsoft.com/en-us/library/dd997365(v=vs.110).aspx