2013-01-31 63 views
0

我加載一個文本的大數據文件並將其顯示在數據網格中, 問題是,窗口很慢並且不平滑, 我該如何實現下面的代碼更好?使Wpf更加平滑

按鈕代碼:

 private async void MILoadLogFile_Click(object sender, RoutedEventArgs e) { 
     // Configure open file dialog box 
     OpenFileDialog oFD = new OpenFileDialog(); 

     // Did they click on the OK button? 
     if (oFD.ShowDialog() == true) { 
      await myLogSession.LoadfromFileAsync(oFD.FileName); 
     } 
    } 

的LOCAD方法:(抱歉長碼)

 public async Task LoadfromFileAsync(String fileName) { 

     compassLogCollection.Clear(); 

     StreamReader streamReader = new StreamReader(fileName); 
     if (fileName.Contains("Compass")) { 
      String temp = ""; 
      String line; 

      DateTime dateTime = new DateTime(); 
      LoggingLvl loggingLvl = new LoggingLvl(); 
      LoggingLvl.ELoggingLvl eLoggingLvl = new LoggingLvl.ELoggingLvl(); 
      char[] delimiters = new[] {' '}; 
      string threadId = ""; 
      string loggingMessage; 
      string dateAndTimestamp = ""; 
      int ff = 0; 

      try { 
       using (streamReader) { 
        while ((line = await streamReader.ReadLineAsync()) != null) { 
         //while ((line = streamReader.ReadLine()) != null) { 
         string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); 


         foreach (string t in parts) { 
          switch (ff) { 
           case 0: 
            dateAndTimestamp = t; 
            break; 
           case 1: 
            dateAndTimestamp += " " + t.Replace(",", "."); 
            dateTime = DateTime.Parse(dateAndTimestamp); 
            dateAndTimestamp = ""; 
            break; 
           case 2: 
            eLoggingLvl = loggingLvl.ParseLoggingLvl(t); 
            break; 
           case 3: 
            threadId = t; 
            break; 

           default: 
            temp += t; 
            break; 
          } 

          ff++; 
         } 
         loggingMessage = temp; 

         temp = ""; 
         ff = 0; 

         loggingLvl = new LoggingLvl(eLoggingLvl); 
         CompassLogData cLD = new CompassLogData(dateTime, loggingLvl, threadId, loggingMessage); 
         compassLogCollection.Add(cLD); 
        } 
        Console.Out.WriteLine("DOOOOOOOOOOOOONE"); 
       } 
      } catch (Exception e) { 
       Console.WriteLine("The file could not be read:"); 
       Console.WriteLine(e.Message); 
      } 
     } 
    } 
+0

顯示你綁定到UI的位置 – Paparazzi

回答

0

我沒有看到你的代碼,其中的UI更新的任何地方,所以我假設是什麼導致緩慢的是從磁盤讀取數據。您可以嘗試將線程從磁盤讀取數據的優先級設置爲低於Normal的值,以便UI線程在CPU週期內擁有更好的機會。請參閱thread priority property

此外,如果文件中行的長度不是很大,並且讀取該文件的代碼已經在後臺線程中運行,那麼我只需使用ReadLine而不是使用ReadLineAsync並將工作傳遞給另一個線。

+0

可以給我一個例子,說明如何設置ThreadPriority – persianLife

+0

@pars你可以查看文檔@ MSDN http://msdn.microsoft.com/en-us/library /system.threading.thread.priority.aspx – kenny

+0

您可以使用[此屬性](http://msdn.microsoft.com/en-us/library/system.threading.thread.currentthread.aspx),但您需要確定你沒有在UI線程上設置它。如果你在'LoadFromFileAsync'裏面做,應該這樣做。 – Ameen