-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;
}
}
在此先感謝
謝謝它現在適用於一些調整。我使用DownloadStringTaskAsync而不是DownloadStringAsync – lorigio 2013-04-06 17:15:19