2012-11-09 23 views
-4

我有一些操作(我使用WPF)。我不會在單獨的線程中運行它們。 我該怎麼辦?線程在WPF操作

實施例:

foreach (string d in Directory.GetDirectories(sDir)) 
{ 
    foreach (string f in Directory.GetFiles(d, txtFile.Text)) 
    { 
     lstFilesFound.Items.Add(f); 
    } 
    DirSearch(d); 
} 
+0

請詳細說明您的問題和想要的內容! – moorara

+0

所以你只是想在它自己的線程中運行下面的代碼,然後返回,以便你的應用程序可以繼續運行?什麼是DirSearch ...你在這裏顯示的函數基本上遞歸地獲取各個子文件夾中的文件? – DRapp

回答

2

如果使用.NET 4,則可以使用Task Parallel Library

剛剛在C#.NET示例4控制檯應用程序:

internal class Program 
    { 
     private static readonly object listLockObject = new object(); 
     private static readonly IList<string> lstFilesFound = new List<string>(); 
     private static readonly TxtFile txtFile = new TxtFile("Some search pattern"); 
     private static string sDir = "Something"; 


     public static void Main() 
     { 
      Parallel.ForEach(Directory.GetDirectories(sDir), GetMatchingFolderAndDoSomething); 
     } 

     private static void GetMatchingFolderAndDoSomething(string directory) 
     { 
      //This too can be parallelized. 
      foreach (string f in Directory.GetFiles(directory, txtFile.Text)) 
       { 
        lock (listLockObject) 
        { 
         lstFilesFound.Add(f); 
        } 
       } 

      DirSearch(directory); 
     } 

     //Make this thread safe. 
     private static void DirSearch(string s) 
     { 
     } 

     public class TxtFile 
     { 
      public TxtFile(string text) 
      { 
       Text = text; 
      } 

      public string Text { get; private set; } 
     } 
    } 
1

如果」重新使用WPF並需要使用多線程,您將不得不以Separating the UI from the business logic開頭,否則您將以無盡的Dispatcher.Invoke()調用鏈結束。

另一個答案還指出,請參閱任務並行庫以簡化多線程應用程序的開發,但請注意WPF UIElements的屬性只能由創建它們的線程(通常稱爲分派器線程)訪問。