7

我正在编写一个多线程下载管理器,其中下载信息由我编写的一个类(称为 DownloadOperation)管理。下载保存在一个列表中(称为下载)。当类 (queryCompleted) 中的函数返回 true 但发现无法从foreach循环内的列表中删除元素时,我需要从列表中删除对象。达到相同效果的最佳方法是什么?我对 C# 比较陌生,所以请原谅我的愚蠢。

private void removeInactiveDownloads()
    {
        foreach (DownloadOperation dl in download)
        {
            if (dl.queryComplete() == true)
            {
                // if download is no longer in progress it is removed from the list.
                download.Remove(dl);
            }
        }
    }
4

3 回答 3

15

List<T>有方法

public int RemoveAll(
    Predicate<T> match
)

删除与谓词匹配的所有元素:http: //msdn.microsoft.com/en-us/library/wdka673a.aspx

因此,我建议类似:

download.RemoveAll(x => x.queryComplete());

(请注意,这== true不是必需的,因为.queryComplete()已经返回 true 或 false!)

于 2013-07-02T23:42:58.830 回答
3

在 For 循环而不是 Foreach 循环中向后迭代

for(int i = download.Count; i >= 0; i--)
{
    if (download[i].queryComplete())
    {
       // if download is no longer in progress it is removed from the list.
       download.RemoveAt(i);
    }
}
于 2013-07-02T23:42:23.343 回答
1

Patashu's answer is the best solution in general, but based on your example code I would suggest taking another approach altogether.

Are you polling the download list periodically to find the completed ones? Event subscription would probably be a better solution. Since you're new to C#, in case you didn't know the language has built-in support for this pattern: Events

A download could raise a Completed event when it completes, which is subscribed to by the code which manages the list, something like:

private void AddDownload(DownloadOperation dl) {
    download.Add(dl);
    dl.Completed += (s, e) => download.Remove(dl);
}
于 2013-07-03T00:30:55.187 回答