2013-04-06 103 views
-1

我有這樣的代碼,反序列化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)); 
    } 

取和反序列化功能

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; 
     } 
    } 

在此先感謝

回答

1

裏面你Fetch方法,你也應該使用伺機通過從Web客戶端下載您的字符串數據將其更改爲:

json = await client.DownloadStringAsync(new UriBuilder("my url" + RealmName).Uri);     

而是採用了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方法,您可以自動將任務展開到布爾,然後您可以繼續在UI線程上執行代碼。

+0

謝謝它現在適用於一些調整。我使用DownloadStringTaskAsync而不是DownloadStringAsync – lorigio 2013-04-06 17:15:19