螺纹同时工作

时间:2009-09-09 18:53:01

标签: c# multithreading

有一个包含100个字符串URI的字符串数组myDownloadList。我想启动5个线程作业,它们将从myDownloadList(如堆栈)弹出下一个URI并对其执行某些操作(下载它),直到堆栈上没有剩余URI(myDownloadList)。

这样做的最佳做法是什么?

2 个答案:

答案 0 :(得分:6)

使用ThreadPool,然后设置所有请求。 ThreadPool会自动安排它们。

使用任务并行库,.NET 4将变得更容易。将每个请求设置为Task非常有效且容易。

答案 1 :(得分:1)

确保每个线程在访问时锁定myDownloadList。您可以使用递归来获取最新的,然后当列表为0时,它可以停止该功能。

请参阅下面的示例。

public static List<string> MyList { get; set; }
public static object LockObject { get; set; }

static void Main(string[] args)
{
    Console.Clear();

    Program.LockObject = new object();

    // Create the list
    Program.MyList = new List<string>();

    // Add 100 items to it
    for (int i = 0; i < 100; i++)
    {
        Program.MyList.Add(string.Format("Item Number = {0}", i));
    }

    // Start Threads
    for (int i = 0; i < 5; i++)
    {
        Thread thread = new Thread(new ThreadStart(Program.PopItemFromStackAndPrint));

        thread.Name = string.Format("Thread # {0}", i);

        thread.Start();
    }
} 


public static void PopItemFromStackAndPrint()
{
    if (Program.MyList.Count == 0)
    {
        return;
    }

    string item = string.Empty;

    lock (Program.LockObject)
    {
        // Get first Item
        item = Program.MyList[0];

        Program.MyList.RemoveAt(0);
    }

    Console.WriteLine("{0}:{1}", System.Threading.Thread.CurrentThread.Name, item);

    // Sleep to show other processing for examples only
    System.Threading.Thread.Sleep(10);

    Program.PopItemFromStackAndPrint();
}
相关问题