ReportProgress是否必须在c#中的DoWork Ba​​ckground方法中完成?

问题描述:

我有一个收集视频列表数据的应用程序。我希望实时更新进度和文件名。我是否必须将所有检查这些文件的代码放在bw_DoWork方法中?ReportProgress是否必须在c#中的DoWork Ba​​ckground方法中完成?

目前我有这种方法,但bw.ReportProgress工作不正确。

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()); 
    } 

我的DoWork方法是这样的:

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

      if ((worker.CancellationPending == true)) 
      { 
       e.Cancel = true; 

      } 

}

+1

您在滥用BackgroundWorker。 – SLaks 2010-12-12 03:12:22

我必须把所有的检查在bw_DoWork方法这些文件的代码?

否,代码不必在物理存在,但你必须呼叫从DoWork的代码。目前您的DoWork方法没有做任何事情。

还请记住在BackgroundWorker上设置属性WorkerReportsProgresstrue。你可以在设计师那里做到这一点。

 bw.ReportProgress(counter/completeMovieList.Count); 

这是一个整数除法,1/2 = 0,而不是0.5。由于计数器永远不会大于计数,表达式总是会生成0.一种可能的修复方法是计算百分比:

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