c#简单等待线程队列(队列已满时等待)从Sharepoint下载多个文件

时间:2013-06-14 14:10:34

标签: c# multithreading sharepoint queue download

我编写了一个简单的程序,可以使用线程从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;
    }



}

1 个答案:

答案 0 :(得分: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();
}