2013-04-06 2 views
-1

나는 URL에서 JSON을 역 직렬화하지만 GUI는 여전히 차단됩니다 그리고 난 내가 순서를 작성해야합니까 얼마나 **C# 작업을 차단 UI

그것을 밖으로 정렬하는 방법을 모르는이 코드를 내가 뭔가를 게시 할 수 stackoverflow? "귀하의 게시물이 주로 코드 인 것 같습니다. 자세한 내용을 추가하십시오."

버튼 코드 :

private void button1_Click(object sender, EventArgs e) 
    { 
     var context = TaskScheduler.FromCurrentSynchronizationContext(); 
     string RealmName = listBox1.Items[listBox1.SelectedIndex].ToString(); 
     Task.Factory.StartNew(() => JsonManager.GetAuctionIndex().Fetch(RealmName) 
     .ContinueWith(t => 
     { 
      bool result = t.Result; 
      if (result) 
      { 
       label1.Text = JsonManager.GetAuctionIndex().LastUpdate + " ago"; 
       foreach (string Owner in JsonManager.GetAuctionDump().Fetch(JsonManager.GetAuctionIndex().DumpURL)) 
       { 
        listBox2.Items.Add(Owner); 
       } 
      } 
     },context)); 
    } 

기능 당신은 또한하여 웹 클라이언트에서 문자열 데이터를 다운로드 할 기다리고 있습니다 사용해야 당신의 Fetch 방법 내부 사전

답변

1

에서

public async Task<bool> Fetch(string RealmName) 
    {   
     using (WebClient client = new WebClient()) 
     { 
      string json = ""; 
      try 
      { 
       json = client.DownloadString(new UriBuilder("my url" + RealmName).Uri);     
      } 
      catch (WebException) 
      { 
       MessageBox.Show(""); 
       return false; 
      } 
      catch 
      { 
       MessageBox.Show("An error occurred"); 
       Application.Exit(); 
      } 
      var results = await JsonConvert.DeserializeObjectAsync<RootObject>(json); 

      TimeSpan duration = DateTime.Now - Utilities.UnixTimeStampToDateTime(results.files[0].lastModified); 
      LastUpdate = (int)Math.Round(duration.TotalMinutes, 0); 
      DumpURL = results.files[0].url; 
      return true; 
     } 
    } 

감사합니다 가져 오기 및 역 직렬화 변경 :

그리고 대신 사용해야 연속으로 Task를 사용하는 공은 버튼 이벤트 핸들러도 기다리고 있습니다 :

private async Task button1_Click(object sender, EventArgs e) 
{ 
    string RealmName = listBox1.Items[listBox1.SelectedIndex].ToString(); 

    bool result = await JsonManager.GetAuctionIndex().Fetch(RealmName); 
    if (result) 
    { 
     label1.Text = JsonManager.GetAuctionIndex().LastUpdate + " ago"; 
     foreach (string Owner in await JsonManager.GetAuctionDump().Fetch(JsonManager.GetAuctionIndex().DumpURL)) 
     { 
      listBox2.Items.Add(Owner); 
     } 
    } 
} 

을 계속하면 이제 C# 컴파일러에 의해 설정입니다. 기본적으로 UI 스레드에서 계속 진행되므로 현재 동기화 컨텍스트를 수동으로 캡처 할 필요가 없습니다. Fetch 메서드를 기다리면 작업이 bool에 자동으로 unwrap 된 다음 UI 스레드에서 코드를 계속 실행할 수 있습니다.

+0

일부 조정을 해 주셔서 감사합니다. DownloadStringAsync 대신 DownloadStringTaskAsync를 사용했습니다. – lorigio