.net 从网站下载字符串时停止表单冻结
在我的应用程序中,我有一个web客户端,它应该从网站下载一个字符串。它下载了相当多的文本,大约20行左右。但是,当我下载文本时,GUI在下载时冻结,然后在下载完成后恢复。我怎样才能防止这种情况.net 从网站下载字符串时停止表单冻结,.net,vb.net,freeze,webclient-download,.net,Vb.net,Freeze,Webclient Download,在我的应用程序中,我有一个web客户端,它应该从网站下载一个字符串。它下载了相当多的文本,大约20行左右。但是,当我下载文本时,GUI在下载时冻结,然后在下载完成后恢复。我怎样才能防止这种情况 我使用的是Visual Basic 2010、.NET 4.0、Windows窗体和Windows 7 x64。在工作线程而不是GUI线程中执行时间密集型任务。这将防止事件循环冻结。可用于此操作 PS:虽然您可以将此模板用于任何没有异步版本的方法,但WebClient.DownloadString确实有一
我使用的是Visual Basic 2010、.NET 4.0、Windows窗体和Windows 7 x64。在工作线程而不是GUI线程中执行时间密集型任务。这将防止事件循环冻结。可用于此操作
PS:虽然您可以将此模板用于任何没有异步版本的方法,但WebClient.DownloadString确实有一个,因此我会选择Karl Anderson的答案另一种选择是使用
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调用异步获取字符串。要获得更多帮助,请发布一些代码。这很性感。对于
WebClient
也有异步方法。你是认真的吗@DonA如果是关于我删除的评论:我以为你说的是async/await(WebClient.DownloadStringTaskAsync)
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