简体   繁体   中英

loop optimization in c#

I am working on a music player for pc using c# and all seems to go fine but, i have problem in loading all the music files from the music directory because it loads very slowly and this take time when opening the app, it could take 5 min depending on the amount of music files. I think this happens because i created a loop to loop through each music file and get the metadatas and also the picture to load on different picture boxes for each music file.
Please Help, i need it to be faster. Thank you. the code is below...

    public List<MusicDetails> Music_Library()
    {


         List<MusicDetails> files = new List<MusicDetails>();
        string[] musicfolder = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),"*mp3", SearchOption.AllDirectories);


        for (int i = 0; i <musicfolder.Length; i++)
        {
            try {
                files.Add(new MusicDetails
                {
                    title = TagLib.File.Create(musicfolder[i]).Tag.Title,
                    genre = TagLib.File.Create(musicfolder[i]).Tag.FirstGenre,
                    artist = TagLib.File.Create(musicfolder[i]).Tag.FirstPerformer,
                    path = musicfolder[i],
                    CoverArt = OrganiseAlbums.SingleAlbumImage(musicfolder[i],true)


                });
            }catch(Exception)
            {
              // OMIT FILE
            }  
        }
        return files;

    }

You could try replacing your loop with a parallel foreach loop using background threads - add each item to the UI as it is processed, and let .Net determine the most efficient way to process everything. If you do it right, your UI will remain responsive, and your users will start out with "enough to look at..." Here is a link to get you started:

https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

If you have a ton of music files, though, you may not want to load them all into memory at once. I would look into some sort of a list control or layout control that allows virtualization so that you instantiate and display only the visible ones at any given time. Use a tutorial to see how to bind to your collection so that it is virtualized.

If you post a more specific question with examples of what you have tried, you will get more specific answers...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM