L.Farci L.Farci - 3 months ago 36
C# Question

C# WinForm progress bar not progressively increasing

So I've made a simple Mp3 to Wave converter using NAudio. Everything works fine, except that there is a bug that I really don't like. Here's the section of the code that does the conversion:

foreach (mp3file file in fileList){
string outputfilename = fbd.SelectedPath + "\\" + file.name + ".wav";
using (Mp3FileReader reader = new Mp3FileReader(file.path)){
using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader)){
WaveFileWriter.CreateWaveFile(outputfilename, convertedStream);
}
}
progressBar.PerformStep(); //This isn't working.
}


I wanted the program to make the progressbar perform a step each time a song gets converted, but instead the progress bar stays empty for the entire conversion process and then increases all at once when the conversion is finished.
It's not that worrying tho, if there's not simple solution I'll bear this bug.

Answer

Your Conversion and progressbar updation is taking place on same thread so updating the GUI components do not take place until the conversion is completed just use Application.doEvents() as it will process all pending messages in que of application after progressbar.PerformStep() then it will not fill up at once at the end of processing but keeps on updating with the processing

foreach (mp3file file in fileList){
        string outputfilename = fbd.SelectedPath + "\\" + file.name + ".wav";
        using (Mp3FileReader reader = new Mp3FileReader(file.path)){
            using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader)){
               WaveFileWriter.CreateWaveFile(outputfilename, convertedStream);
            }
        }
        progressBar.PerformStep(); //This isn't working alone
        Application.DoEvents();   //This is working fine now
    }