开发者

Does ReportProgress have to be done in the DoWork Background method in c#?

开发者 https://www.devze.com 2023-01-29 22:11 出处:网络
I have an app that collects data on a list of videos. I want the progress and filenames to be updated in real time. Do I have to place all the code that examines those files in the bw_DoWork method?

I have an app that collects data on a list of videos. I want the progress and filenames to be updated in real time. Do I have to place all the code that examines those files in the bw_DoWork method?

Currently I have this method, but the bw.ReportProgress isn't working right.

private void GetMovieData(List<FileInfo> completeMovieList)
    {
        List<string> movieLists = new List<string>();

        int counter = 0;
        foreach (FileInfo movie in completeMovieList)
        {
            counter++;
            string[] movieData = new string[3];

            bw.ReportProgress(counter / completeMovieList.Count);


            // get last modified date
            string movieLastModified = string.Concat(movie.LastWriteTime.Year + "/" + movie.LastWriteTime.Month + "/" + movie.LastWriteTime.Day);

            // get duation of video
            string lengthOfVideo = Program.GetDetails(movie);

            if (!movieListWithData.ContainsKey(movie.Name))
            {
                movieData[0] = lengthOfVideo;
                movieData[1] = movieLastModified;
                movieData[2] = movie.FullName;
                movieListWithData.Add(movie.Name, movieData);

            }

            movieLists.Add(movie.FullName + "|" + lengthOfVideo + "|" + movieLastModified);

        }

        StringBuilder sb = new StringBuilder();

        foreach (KeyValuePair<string, string[]> key in movieListWithData)
        {
            sb.AppendLine(key.Key + "|" + key.Value[0] + "|" + key.Value[1] + "|" + key.Value[2]);
        }

        File.WriteAllText(Program.movieTxtFileLocalPath, sb.ToString());
    }

My DoWork method looks like:

private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

            if ((worker.CancellationPending == true))
            {
                e.Can开发者_StackOverflow中文版cel = true;

            }

}


Do I have to place all the code that examines those files in the bw_DoWork method?

No, the code doesn't have to physically be there, but you have to call the code from DoWork. Currently your DoWork method isn't doing anything.

Also remember to set the property WorkerReportsProgress to true on your BackgroundWorker. You can do this in the designer.


        bw.ReportProgress(counter / completeMovieList.Count);

That's an integer division, 1 / 2 = 0, not 0.5. Since counter will never be larger than Count, the expression always produces 0. One possible fix is to calculate a percentage:

        bw.ReportProgress(100 * counter / completeMovieList.Count);
0

精彩评论

暂无评论...
验证码 换一张
取 消