2013-08-29 19 views
1

我只是在vb.net做了一个FTP聊天,并从FTP服务器 文件更新消息,所以我加一个计时器间隔1000这个代码如何从FTP下载不形滞后vb.net

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

您需要在不同的线程上运行下载操作以避免UI线程滞后。 – Arpit

+0

可能的重复[如何在此上下文中使用WebClient.DownloadDataAsync()方法?](http://stackoverflow.com/questions/1585985/how-to-use-the-webclient-downloaddataasync-method-in-this -context) –

+1

FTP聊天。哇。应该在DWTF比赛中输入。 – Will

回答

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; 
} 

您也可以通过处理进度变化事件添加进度指示器。

+0

我在client.DownloadStringAsync(“ftp://185.**.***.**/htdocs/chat.txt “)--->字符串类型的值不能转换为uri ... –

+0

检查示例代码。忘记添加'新':P – Arpit

+0

稍微修改一下代码我就明白了谢谢,它的工作非常完美! –

0

最好的方法是使用框架提供的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 
+0

为什么?当WebClient有自己的异步方法 –

+0

@AppDeveloper它不工作... –

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 

希望它帮助。

+0

请记住,您必须使用'thread_start'函数,而不是'check_for_changes'本身。 – aliqandil