2013-08-29 21 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