2014-09-26 5 views
0

WP 8.1에서 응용 프로그램을 작성 중입니다. 내 방법 중 하나는 HTML을 구문 분석하고 모든게 괜찮 았어. 하지만 폴란드 문자를 사용하도록 코딩을 변경하고 싶습니다. 그래서 변수 길이가 byte [] 인 속성을 가져야합니다. 이것을 가능하게하기 위해서는을 으로 사용하고 asnych에 내 방법을 변경해야합니다.비동기, 기다리고 이상한 결과

public async void GetTimeTable(string href, int day) 
{ 
    string htmlPage = string.Empty; 
    using (var client = new HttpClient()) 
    { 
     var response = await client.GetByteArrayAsync(URL); 

     char[] decoded = new char[response.Length]; 
     for (int i = 0; i < response.Length; i++) 
     { 
      if (response[i] < 128) 
       decoded[i] = (char)response[i]; 
      else if (response[i] < 0xA0) 
       decoded[i] = '\0'; 
      else 
       decoded[i] = (char)iso8859_2[response[i] - 0xA0]; 
     } 
     htmlPage = new string(decoded); 
    } 

    // further code... and on the end:: 
    TimeTableCollection.Add(xxx); 
} 

public ObservableCollection<Groups> TimeTableCollection { get; set; } 

방법은 MainPage.xaml.cs를

에서
vm.GetTimeTable(navContext.HrefValue, pivot.SelectedIndex); 
TimeTableViewOnPage.DataContext = vm.TimeTableCollection; 

를 호출 그리고 지금 내 질문입니다. vm.TimeTableCollection이 null 인 이유는 무엇입니까? 비동기를 사용하지 않고 모든 것이 괜찮 으면 vm.TimeTableCollection에 x 요소가 있습니다.

+0

'GetTimeTable'을 기다리지 않으므로 컨트롤이 완료되기 전에 다음 줄로 계속 진행됩니다. 이에 대한 많은 예제가 있습니다. –

답변

1

이제 내 질문입니다. vm.TimeTableCollection이 null 인 이유는 무엇입니까?

await없이 async 작업을 실행하고 있기 때문에. 따라서 다음 줄에 vm 속성에 액세스하면 요청이 완료되지 않을 수 있습니다.

당신은 async Taskawait을 당신의 방법 서명을 변경해야 다음

public async Task GetTimeTableAsync(string href, int day) 
{ 
    string htmlPage = string.Empty; 
    using (var client = new HttpClient()) 
    { 
     var response = await client.GetByteArrayAsync(URL); 

     char[] decoded = new char[response.Length]; 
     for (int i = 0; i < response.Length; i++) 
     { 
      if (response[i] < 128) 
       decoded[i] = (char)response[i]; 
      else if (response[i] < 0xA0) 
       decoded[i] = '\0'; 
      else 
       decoded[i] = (char)iso8859_2[response[i] - 0xA0]; 
     } 
     htmlPage = new string(decoded); 
    } 

    // further code... and on the end:: 
    TimeTableCollection.Add(xxx); 
} 

과 :

await vm.GetTimeTableAsync(navContext.HrefValue, pivot.SelectedIndex); 

이것은 당신의 최고 호출하는 방법뿐만 아니라 비동기하게하는 것을 의미한다. 이것은 일반적으로 비동기 메서드를 처리 할 때의 동작입니다. async all the way이 필요합니다.

await vm.GetTimeTable(navContext.HrefValue, pivot.SelectedIndex); 
TimeTableViewOnPage.DataContext = vm.TimeTableCollection; 

당신이 돈이 ': TPL의 지침을 따르지

참고, 당신은 Async 후위 어떤 async 방법을 표시해야합니다, 따라서 GetTimeTable 당신은 결과를 기다리고하지 않을 GetTimeTableAsync

0

해야한다 t await 비동기 메서드를 실행하면 프로그램이이를 실행하고 완료 될 때까지 기다리지 않고 다음 코드를 계속 실행합니다.

관련 문제