在我的应用程序中,我有一个Web客户端应该从网站下载字符串。它下载了大量的文本,大约20行左右。但是,当我下载文本时,GUI会在下载时冻结,然后在完成下载后恢复。我怎样才能防止这一点?当从网站下载字符串时停止窗体冻结
我使用的是Visual Basic 2010,.NET 4.0,Windows Forms和Windows 7 x64。
在我的应用程序中,我有一个Web客户端应该从网站下载字符串。它下载了大量的文本,大约20行左右。但是,当我下载文本时,GUI会在下载时冻结,然后在完成下载后恢复。我怎样才能防止这一点?当从网站下载字符串时停止窗体冻结
我使用的是Visual Basic 2010,.NET 4.0,Windows Forms和Windows 7 x64。
在工作线程中执行时间密集型任务,而不是在GUI线程上执行。这将防止事件循环冻结。
您可以使用Task Parallel Library这
Task.Factory.StartNew(() =>
{
using (var wc = new WebClient())
{
return wc.DownloadString("http://www.google.com");
}
})
.ContinueWith((t,_)=>
{
textBox1.Text = t.Result;
},
null,
TaskScheduler.FromCurrentSynchronizationContext());
PS:虽然你可以使用这个模板不具有异步版本的任何方法,WebClient.DownloadString确实有一个,所以我会选择卡尔·安德森回答
那就是性感。也有'WebClient'的异步方法。 – OneFineDay
你是认真的,我使用! – OneFineDay
@DonA如果是关于我的删除评论:我以为你在谈论* async/await(WebClient.DownloadStringTaskAsync)* – I4V
另一种替代方法是使用DownloadStringAsync
,这将触发来自UI线程的请求,但它不会阻塞线程,因为它是异步请求。以下是使用示例DownloadStringAsync
:
Public Class Form1
Private Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)
' Did the request go as planned (no cancellation or error)?
If e.Cancelled = False AndAlso e.Error Is Nothing Then
' Do something with the result here
'e.Result
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim wc As New WebClient
AddHandler wc.DownloadStringCompleted, AddressOf AlertStringDownloaded
wc.DownloadStringAsync(New Uri("http://www.google.com"))
End Sub
End Class
使用AJAX调用异步获取字符串。如需更多帮助,请发布一些代码。 – 2013-08-06 01:24:56