2012-11-09 3 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를 사용하는 경우, 당신은 C# .NET에서 Task Parallel Library

그냥 예를 사용할 수 있습니다 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의 속성은 스레드를 생성 한 스레드 (일반적으로 Dispatcher 스레드라고 함)에서만 액세스 할 수 있다는 점에 유의하십시오.