0

我编写了一个简单的程序来使用线程同时从 Sharepoint 下载多个文件。我使用了 Do While 循环来确保程序在队列满时等待。

请在下面的代码中查看我的评论。我正在寻找一种更有效的方式让程序在队列已满时等待。使用 Do While 循环我的程序有 70% 的 cpu 使用率,通过添加 Thread.Sleep(1000),它减少到 30% 的 CPU 使用率,但我认为必须有更有效的方法,同时不损害性能队列?谢谢

// Main Program to dispatch Threads to download files from Sharepoint
bool addedtoDownloader;
                    do
                    {
                        addedtoDownloader = ThreadDownloader.addJob(conn, item.FileRef, LocalFolderPath);

                       // ===== by having the following 2 lines below reduce CPU usage
                            if (addedtoDownloader == false)
                            System.Threading.Thread.Sleep(1000);
                       // ====== Is there a better way to do this? ================
                    }
                    while (addedtoDownloader == false);





class ThreadDownloader
{
    public const int MaxThread = 15;

    public static List<Thread> ThreadList = new List<Thread>();


    public static bool addJob(ClientContext conn, string SrcFileURL, string DestFolder)
    {
        RefreshThreadList();

        if (ThreadList.Count() < MaxThread)
        {

            Thread t = new Thread(() => Program.DownloadFile(conn, SrcFileURL, DestFolder));
            ThreadList.Add(t);
            t.Start();
            return true;
        }

        return false;


    }

    public static void RefreshThreadList()
    {
        List<Thread> aliveThreadList = new List<Thread>();

        foreach (var t in ThreadList)
        {
            if (t.IsAlive)
            {
                aliveThreadList.Add(t);
            }
        }

        ThreadList.Clear();
        ThreadList = aliveThreadList;
    }



}
4

1 回答 1

0

这似乎是信号量的一个很好的用例:

private static SemaphoreSlim semaphore = new SemaphoreSlim(MaxThread);

public static void addJob(ClientContext conn, string SrcFileURL, string DestFolder)
{
    semaphore.Wait();

    RefreshThreadList();

    Thread t = new Thread(() =>
        {
            try
            {
                Program.DownloadFile(conn, SrcFileURL, DestFolder);
            }
            finally
            {
                semaphore.Release();
            }
        });
    ThreadList.Add(t);
    t.Start();
}
于 2013-06-14T16:17:24.580 回答