1

我刚刚在 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我能做什么?

4

3 回答 3

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

您还可以通过处理进度更改事件来添加进度指示器。

于 2013-08-29T15:12:59.790 回答
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
于 2013-08-29T15:08:35.263 回答
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

希望能帮助到你。

于 2013-08-29T16:30:13.413 回答