C# WPF更改URI异步
我的页面中有一个名为C# WPF更改URI异步,c#,wpf,asynchronous,C#,Wpf,Asynchronous,我的页面中有一个名为LinkURL的文本框。我试图用它的文本值创建Uri。并使用BitmapImage的Uri。因此,用户可以在键入URL时看到图像 但我的UI冻结,应用程序停止运行。我想用它来预览图像 public void LoadImage(object sender, TextChangedEventArgs e) { Uri uri = null; Dispatcher.BeginInvoke(new Action(delegate { uri
LinkURL
的文本框。我试图用它的文本值创建Uri。并使用BitmapImage
的Uri。因此,用户可以在键入URL时看到图像
但我的UI冻结,应用程序停止运行。我想用它来预览图像
public void LoadImage(object sender, TextChangedEventArgs e)
{
Uri uri = null;
Dispatcher.BeginInvoke(new Action(delegate
{
uri = new Uri(this.LinkURL.Text);
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(uri, wc);
}));
}
private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = e.Result;
this.Preview.Source = bi;
}
我试过了,但没用
UI冻结并向我提供
系统。反射。TargetInvocationException
或ArgumentNullException
,“没有工作”并不是什么好事情。你能说得更具体一点吗?你忘了叫Endinit,你的BeginInvoke也没用;代码仍将在UI线程上执行。仅仅使用OpenReadAsync通常就足以避免阻塞UI。(我说“通常”是因为OpenReadAsync会同步执行一些操作,比如DNS解析)为了添加到@ThomasLevesque的注释中,Dispatcher.BeginInvoke
无助于避免UI阻塞,如果DNS解析在OpenReadAsync
内部同步进行,它只会延迟它。检查解决方案。