none
同一段代码,在控制台和在wpf后台执行的情况不一样。 RRS feed

  • 问题

  • private async Task<Stream> GetWebPageAsync()
            {
                using (var httpClient = new HttpClient())
                {
                    var stream = await httpClient.GetStreamAsync("http://www.baidu.com");
                    return stream;
                }
            }
    
            private async void Button_Click()
            {
                using (Stream stream = await GetWebPageAsync())
                using (var fileStream = new FileStream(@"c:\msg.bin", FileMode.OpenOrCreate))
                {
                    var state = stream.CanRead;
                    await stream.CopyToAsync(fileStream);
                    //    StatusLabel.Content = "Done...";
                }
            }

    同样是这段代码,在控制台中,button_Click中的state 为false,而在wpf后台的state为true

    (wpf后台的Button_Click有(object sender, RoutedEventArgs e)参数)

    2015年4月2日 8:19

答案

  • 你好:

    我测试了一下,GetWebPageAsync方法return之前CanRead为true,但是return之后就为false了,我暂时也不太清楚原因,但是稍微修改一下就可以避免这个问题:

    private async void Button_Click()
            {
                //using (Stream stream = await GetWebPageAsync())
                using (Stream stream = await new HttpClient().GetStreamAsync("http://www.baidu.com"))
                {
    
    
                    using (var fileStream = new FileStream(@"d:\msg.txt", FileMode.OpenOrCreate))
                    {
                        var state = stream.CanRead;
    
                        await stream.CopyToAsync(fileStream);
                        //    StatusLabel.Content = "Done...";
                    }
                }
            }


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    2015年4月16日 7:55
    版主