代码适用于控制台应用程序,而不适用于Wpf

时间:2015-06-08 17:01:15

标签: c# wpf asynchronous console async-await

所以我在Jon Skeet的深度书中读过C#,关于async / await。

这是在控制台应用程序上运行的代码:

    static void Main(string[] args)
    {
        Console.WriteLine(GetStuff().Result);
    }

    public static async Task<int> GetStuff()
    {
        using (HttpClient client = new HttpClient())
            return (await client.GetStringAsync("http://csharpindepth.com")).Length;
    }


然而,这似乎是死锁。 Wpf应用程序冻结并且从不显示MessageBox。我知道它应该冻结,因为它同步运行,但是,我不明白为什么它永远不会继续。我有一个Button,Button_Click作为事件:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(GetStuff().Result.ToString());
    }

    public static async Task<int> GetStuff()
    {
        using (HttpClient client = new HttpClient())
            return (await client.GetStringAsync("http://csharpindepth.com")).Length;
    }


非常感谢你!

0 个答案:

没有答案
相关问题