异步下载过程中受阻于C#WPF应用程序UI线程 [英] UI Thread blocked in C# WPF App during Async Download
问题描述
我有以下的基本WPF应用程序,在这里我想在文本框中显示的内容。然而,当我点击按钮,UI线程似乎被阻止。我不知道我在做什么错了,因为我抓住从Pluralsight课程的锻炼; Tibial这个文件code。
在XAML和code:
<窗口x:类=AsyncFetch.MainWindow
的xmlns =http://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
的xmlns:X =http://schemas.microsoft.com/winfx/2006/xaml
标题=主窗口HEIGHT =350WIDTH =525>
<网格和GT;
< Grid.RowDefinitions>
< RowDefinition高度=自动/>
< RowDefinition高度=*/>
< /Grid.RowDefinitions> <按钮
X:NAME =getButton
的HorizontalAlignment =左
WIDTH =75
内容=_获取数据
点击=getButton_Click
/> <文本框
X:NAME =dataTextBox
保证金=4
Grid.Row =1
/> < /网格和GT;
< /窗GT;
在code:
命名空间AsyncFetch
{
///<总结>
///为MainWindow.xaml交互逻辑
///< /总结>
公共部分类主窗口:窗口
{
公共主窗口()
{
的InitializeComponent();
} 私人异步无效getButton_Click(对象发件人,RoutedEventArgs E)
{
WebClient的W =新的WebClient(); 字符串的txt =等待w.DownloadStringTaskAsync(http://www.google.com);
dataTextBox.Text = TXT;
}
}
}
这不应该阻止用户界面线程,该技术是正确的。
然而,仅仅因为一个方法是异步,并返回一个任务< T>
,并不能保证的全部的方法(或它的任何)将异步运行。
在 Web客户端
的情况下,控制不会返回给调用者直到请求已经完全后,prepared并启动。随着 Web客户端
,我相信URI preparation,包括所有的DNS查找,可以同步发生,异步部分(实际的请求)开始,前需要哪些可以请求返回之前引起的延迟。
I have the following basic WPF app, where I want the content displayed in the text box. However, when I click on the button, the UI thread seems to be blocking. I am not sure what I am doing wrong, as I grabbed this code from the Excercise files of a Pluralsight course.
The XAML and the code:
<Window x:Class="AsyncFetch.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button
x:Name="getButton"
HorizontalAlignment="Left"
Width="75"
Content="_Get Data"
Click="getButton_Click"
/>
<TextBox
x:Name="dataTextBox"
Margin="4"
Grid.Row="1"
/>
</Grid>
</Window>
The code:
namespace AsyncFetch
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void getButton_Click(object sender, RoutedEventArgs e)
{
WebClient w = new WebClient();
string txt = await w.DownloadStringTaskAsync("http://www.google.com");
dataTextBox.Text = txt;
}
}
}
This shouldn't block the UI thread, and the technique is correct.
However, just because a method is Async, and returns a Task<T>
, doesn't guarantee that the entire method (or any of it) will run asynchronously.
In the case of WebClient
, the control won't return to the caller until after the request has been completely prepared and started. With WebClient
, I believe the URI preparation, including all of the DNS lookups, can happen synchronously and is required before the asynchronous portion (the actual request) begins, which can cause a delay before the request returns.
这篇关于异步下载过程中受阻于C#WPF应用程序UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!