2013-02-24 2 views
0

저는 현재 두 창을 모두 찾고 있습니다. & wp8 apps (모두 sl 및 C# 프로젝트 임).windows dispatchcher, async를 얻는 올바른 방법을 저장합니다.

dispatcher를 가져 오는 것이 wpf와 다르며 Window.Current에서 비동기 메서드 중 일부에서 사라지는 것처럼 보입니다.

내가 할 수있는 것은 기본적으로 App 클래스에 propery를 넣는 것이었지만 안전하지 않은 것처럼 보였습니다. 여기서는 논리를 따르지 않습니다.

것으로 someMethod()가 호출
internal class MainviewModel : ViewModelBase 
{ 
.............. 
    private async void GetLastDocumetAsync() 
    { 
      // Window.Current is null here, but not outside async! 
      await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() => 
      { 
       ObservableCollection<ScannedDocument> docs = await ServiceLocator.DocumentClient.GetLastScannedDocumentsAsync();      
       ScannedDocuments.AddRange(docs); 
       SelectedDocument = ScannedDocuments.LastOrDefault(); 
      } 
    } 
    ... 
    public void SomeMethod(){ 
     // Window.Current is not null 
     Task.Factory.StartNew(() => GetLastDocumetAsync()); 

    } 
} 

, Window.Current가 null가 아닌 :

나는 예를 게시합니다. 우리가 비동기 메서드에있을 때 디스패처가 필요하면 null입니다.

모든 포인터? 명시 적으로 캡처하고 컨텍스트의 복원이 필요하지 않도록

Brgds,

polkaextremist

+0

Windows 운영 체제의 Silverlight? – jv42

답변

2

첫째, 난 강력하게 코드를 구조 조정하기 위해 가능한 한 많이 권장합니다. 평범한 asyncawait 만 사용한다면 컨텍스트를 전혀 캡처 할 필요가 없습니다. 이 같은 것을 할 수있는 귀하의 예제 코드에서

는, StartNew 필요가 없습니다 :

private async Task GetLastDocumentsAsync() 
{ 
    ObservableCollection<ScannedDocument> docs = await ServiceLocator.DocumentClient.GetLastScannedDocumentsAsync();      
    ScannedDocuments.AddRange(docs); 
    SelectedDocument = ScannedDocuments.LastOrDefault(); 
} 

public async Task SomeMethodAsync() 
{ 
    await GetLastDocumentsAsync(); 
    ... 
} 

을 당신이 정말로 명시 적으로 컨텍스트를 캡처하는 필요가 경우에, 나는 당신이 SynchronizationContext을 사용하는 것이 좋습니다. 당신은 일종의 크로스 플랫폼 같다고 생각할 수 있습니다. Dispatcher; my MSDN article에 대한 자세한 정보가 있습니다.

+0

건배! :) 멋진 기사 btw –

관련 문제