c#任务阻止了ui

时间:2013-04-06 15:16:06

标签: c#

我有这个代码从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;
    }
}

1 个答案:

答案 0 :(得分:1)

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

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

而不是使用带有延续的Task,你应该在你的按钮事件处理程序中使用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方法,你自动将任务解包到一个bool,然后你可以继续在UI线程上执行代码。