2017-03-12 1 views
0

내 모든 포함 리소스를 한 번에 비동기 적으로로드하려고합니다.C# 작업 언제, 일부 변수로 작업 연결

private static async Task<String[]> GetResourcesAsync() 
    { 
     var asm = System.Reflection.Assembly.GetEntryAssembly(); 

     var todo = new List<Task<string>>(); 

     foreach (var res in asm.GetManifestResourceNames()) 
     { 
      using (Stream stream = asm.GetManifestResourceStream(res)) 
      using (StreamReader reader = new StreamReader(stream)) 
      { 
       todo.Add(reader.ReadToEndAsync()); 
      } 
     } 

     return await Task.WhenAll(todo); 
    } 

그러나이 방법의 문제는 내가 어떤 자원 corrosponds를 알 방법이 없습니다입니다 배열하는 문자열 :

여기에 내가 가진거야.

내가 사전에 리소스 이름 '고해상도'

덕분에 각 작업을 연결하는 방법에 대한 갈 것이라고 어떻게

+2

시나리오에서 async가 많이 수행하지 않는다는 점에 유의하십시오. GetManifestResourceStream은 메모리에서 직접 읽으므로 동기 작업 만 지원하는 스트림을 반환합니다. –

+0

좋은 점은, 그게 그 문제를 해결하는 한 가지 방법입니다. –

답변

2

당신은 todo 수집 Dictionary<string, Task<string>>을 사용할 수 있습니다합니다 (res 변수가 string입니다) 그리고 당신이 추가 할 수 있습니다 이런 식으로 사전에 : todo.Add(res, reader.ReadToEndAsync());

이 사전에 foreach 때 res-task 쌍을 얻을.

1

그래서 난 그냥 Michael Liu's 의견에 따라이 동기화 롤링 결국

이 그래

그래서 메모리에서 직접 읽기 때문에 GetManifestResourceStream은 동기 작업을 지원하는 스트림을 반환

...

private Dictionary<string, IView> GetViewsFromAssembly() 
    { 
     var asm = System.Reflection.Assembly.GetEntryAssembly(); 

     var views = new Dictionary<string, IView>(); 

     foreach (var res in asm.GetManifestResourceNames()) 
     { 
      using (Stream stream = asm.GetManifestResourceStream(res)) 
      using (StreamReader reader = new StreamReader(stream)) 
      { 
       views.Add(res, new View(reader.ReadToEnd())); 
      } 
     } 

     return views; 
    }