我有这段代码可以从 url 反序列化 JSON,但 GUI 仍然被阻止,我不知道如何解决它。
按钮代码:
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;
}
}