2014-06-26 62 views
0

我編寫了代碼,但它看起來不太優雅和直觀。我現在嘗試重構它。你在我的代碼中看到任何反模式?反模式,重構C#代碼示例

我正在使用圖片。我從文件夾中獲取圖像,處理它並在此之後刪除。

Console.WriteLine("Press ESC to exit"); 
bool isEmptyFolderFlagSet = false; 
while (true) 
{ 
    if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) 
    { 
     appExited(null, EventArgs.Empty); 
     return; 
    }  
    List<string> images = new List<string>(System.Linq.Enumerable.Concat 
     (System.IO.Directory.GetFiles(sourcePath, "*.pdf"), System.IO.Directory.GetFiles(sourcePath, "*.tif"))); 
    if (images.Count == 0 && !isEmptyFolderFlagSet) 
    { 
     Console.WriteLine("Waiting for image..."); 
     isEmptyFolderFlagSet = true; 
    } 
    else 
    { 
     isEmptyFolderFlagSet = false; 
     foreach (string imagePath in images) 
     { 
      try 
      { 
       processing.ProcessingFile(imagePath); 
       System.IO.File.Delete(imagePath); 
      } 
      catch (System.IO.FileNotFoundException ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
     } 
    } 
    Thread.Sleep(500); 
} 
+2

這是一個輪詢循環。所以,而不是Thread.Sleep我會使用一個計時器並定義一個回調。 –

+9

屬於http://codereview.stackexchange.com – jgauffin

回答

2
  1. 放置在一個條件 '而' 條款

    Console.WriteLine("Press ESC to exit"); 
    while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)) 
    {  
        //Code here 
    }  
    
  2. 如果有大量的文件?你應該使用EnumerateFiles而不是GetFiles(將會更快)

  3. 而不是昂貴的try..catch,只捕獲FileNotFound,你可以使用System.IO.File.Exits(filename)方法。

  4. 如前所述,具有回調函數的Timer(可能是匿名的)會更合適。