我刚刚在vb.net中进行了ftp聊天,它从ftp服务器的文件更新消息 所以我用这段代码添加一个间隔为1000的计时器
Try
Dim client As New Net.WebClient
client.Credentials = New Net.NetworkCredential("fnet_1355****", "******")
RichTextBox1.Text = client.DownloadString("ftp://185.**.***.**/htdocs/chat.txt")
Catch ex As Exception
End Try
所以..文件被下载并且它更新文本成功但是有一个问题..每次下载表格都有点滞后...我不喜欢那样:D我能做什么?
答案 0 :(得分:3)
RichTextBox1.Text = client.DownloadString("ftp://185.**.***.**/htdocs/chat.txt")
而不是尝试异步方法。
client.DownloadStringAsync(new Uri("ftp://185.**.***.**/htdocs/chat.txt"))
然后处理下载字符串已完成的事件。
示例代码
client.DownloadStringAsync(new Uri("ftp://185.**.***.**/htdocs/chat.txt"));
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
RichTextBox1.Text =e.Result;
}
您还可以通过处理进度更改事件来添加进度指示器。
答案 1 :(得分:0)
最好的方法是使用Framework提供的ThreadPool
在不同的线程上进行I / O绑定操作。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf DownloadFromFtp))
End Sub
Private Sub DownloadFromFtp()
Try
Dim client As New Net.WebClient
client.Credentials = New Net.NetworkCredential("fnet_1355****", "******")
Dim response As String = client.DownloadString("ftp://185.**.***.**/htdocs/chat.txt")
Me.Invoke(New MethodInvoker(Function() RichTextBox1.Text = response))
Catch ex As Exception
End Try
End Sub
答案 2 :(得分:0)
在我学习PHP之前,这个程序是我设计的。
这里试试这个:
Dim thrd As Threading.Thread
Dim tmr As New Timer
Dim tempstring As String
Private Sub thread_start()
thrd = New Threading.Thread(Sub() check_for_changes())
tmr.Interval = 50
AddHandler tmr.Tick, AddressOf Tick
tmr.Enabled = True
tmr.Start()
thrd.Start()
End Sub
Private Sub Tick(sender As Object, e As EventArgs)
If Not thrd.IsAlive Then
tmr.Stop() : tmr.Enabled = False
RichTextBox1.Text = tempstring
End If
End Sub
Private Sub check_for_changes()
Try
Dim client As New Net.WebClient
client.Credentials = New Net.NetworkCredential("fnet_1355****", "******")
tempstring = client.DownloadString("ftp://185.**.***.**/htdocs/chat.txt")
Catch ex As Exception
End Try
End Sub
希望它有所帮助。