-1

我有这段代码可以从 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;
    }
}
4

1 回答 1

0

在您的Fetch方法中,您还应该使用 await 从 WebClient 下载字符串数据,方法是将其更改为:

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

而不是使用Task带有延续的a,你应该在你的按钮事件处理程序中使用await:

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 方法,您会自动将 Task 解包为 bool,然后您可以继续在 UI 线程上执行代码。

于 2013-04-06T15:22:08.017 回答