在 Visual Basic 中跨线程时正确更新文本框(V​​S 2012 V11) [英] Update Text Box Properly when Cross-threading in Visual Basic (VS 2012 V11)

查看:7
本文介绍了在 Visual Basic 中跨线程时正确更新文本框(V​​S 2012 V11)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 简而言之,这是我的问题:如何使用 BackGroundWorker(或 InvokeRequired 方法)进行线程安全调用以将文本附加到文本框?

这是我的问题,其中包含很多细节和背景:我一直在开发一个程序,该程序将文件从一个位置复制到另一个位置以进行备份.我设置了一个选项,当使用 FileSysteWatcher 修改文件时将保存文件.代码如下:

Here is my question in with much detail and background: I've been working on a program that copies file from one location to another for backup purposes. I set an option that will save a file when the file is modified using the FileSysteWatcher. Here is the code:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim directoryPath As String = Path.GetDirectoryName(TextBox1.Text)
    Dim varFileSystemWatcher As New FileSystemWatcher()
    varFileSystemWatcher.Path = directoryPath

    varFileSystemWatcher.NotifyFilter = (NotifyFilters.LastWrite)
    varFileSystemWatcher.Filter = Path.GetFileName(TextBox1.Text)
    AddHandler varFileSystemWatcher.Changed, AddressOf OnChanged
    varFileSystemWatcher.EnableRaisingEvents = True

End Sub

Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)

    My.Computer.FileSystem.CopyFile(e.FullPath, TextBox2.Text & "" & e.Name, True)
    TextBox3.ApendText("[New Text]") ' This line causes an error
End Sub

除了更新 textbox3 中的文本外,该代码工作正常.当指定的文件被修改时,我需要更新文本框.这一点很重要,这样用户就可以知道程序正在运行并获得程序操作的完整日志.

The code works fine except for updating the text in textbox3. I need the textbox to update when the file specified is modified. This is important so that the user can know the program is working and to have a complete log of the programs operations.

导致的错误是:

跨线程操作无效:控件TextBox3"从线程不是创建它的线程.

Cross-thread operation not valid: Control 'TextBox3' accessed from a thread other than the thread it was created on.

我假设AddHandler varFileSystemWatcher.Changed, AddressOf OnChanged"创建了一个新线程.此外,在OnChange Sub"中更新textbox3"(以我的方式)不是线程安全的方式.所以我做了一些研究,发现了这篇文章:

I'm assuming "AddHandler varFileSystemWatcher.Changed, AddressOf OnChanged" creates a new thread. Also, updating "textbox3" within the "OnChange Sub" (in the way I did) is not a thread-safe manner. So I did some research and found this article:

如何:对 Windows 窗体控件进行线程安全调用

文章解释说,可以使用 InvokeRequired 或 BackgroundWorker 进行线程安全调用.我想使用 BackgroundWorker 进行线程安全调用(如果 InvokeRequired 更有效,那么我将使用它),但是所提供示例的这一部分让我感到困惑:

The article explains that one can use InvokeRequired or a BackgroundWorker to make thread-safe calls. I would like to use the BackgroundWorker to make a thread-safe call (if InvokeRequired is more efficient then I'll use that), but this portion, of the example provied, leaves me confused:

' Do I need these imports to use the BackgroundWorker or InvokeRequired?
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.Windows.Forms

Public Class Form1
   Inherits Form ' Do I need this for what I am trying to do?

   ' This delegate enables asynchronous calls for setting
   ' the text property on a TextBox control.
   Delegate Sub SetTextCallback([text] As String)

   ' This thread is used to demonstrate both thread-safe and
   ' unsafe ways to call a Windows Forms control.
   Private demoThread As Thread = Nothing

   ' This BackgroundWorker is used to demonstrate the 
   ' preferred way of performing asynchronous operations.
   Private WithEvents backgroundWorker1 As BackgroundWorker

   Private textBox1 As TextBox
   Private WithEvents setTextUnsafeBtn As Button
   Private WithEvents setTextSafeBtn As Button
   Private WithEvents setTextBackgroundWorkerBtn As Button

   ' What is this part of the code for and do I need it?
   Private components As System.ComponentModel.IContainer = Nothing

   ' Again, What is this part of the code for and do I need it?
   Public Sub New()
      InitializeComponent()
    End Sub

   ' And again, What is this part of the code for and do I need it?
   Protected Overrides Sub Dispose(disposing As Boolean)
      If disposing AndAlso (components IsNot Nothing) Then
         components.Dispose()
      End If
      MyBase.Dispose(disposing)
    End Sub

上述代码的许多部分让我感到困惑.它有什么作用?我需要这段代码的哪些部分来使用 BackgroundWorker?InvokeRequired 方法的哪些部分?同样,如何使用 BackGroundWorker(或 InvokeRequired 方法)进行线程安全调用以将文本附加到文本框?(很高兴能解释上面的代码,但我真正需要的是如何以线程安全的方式更新文本框的文本的一个示例.)

Many parts of the above code leave me confused. What does it do? What parts of this code do I need to use the BackgroundWorker? What parts for the InvokeRequired method? Again, How do I use the BackGroundWorker (or InvokeRequired method) to make thread-safe calls to append text to a text box? (It'd be great to have the code above explained, but all I really need is one example of how to update the text of a text box in a thread-safe manner.)

推荐答案

更改:

Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)
    My.Computer.FileSystem.CopyFile(e.FullPath, TextBox2.Text & "" & e.Name, True)
    TextBox3.ApendText("[New Text]") ' This line causes an error
End Sub

收件人:

Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)
    My.Computer.FileSystem.CopyFile(e.FullPath, TextBox2.Text & "" & e.Name, True)
    AppendTextBox(TextBox3, "[New Text]")
End Sub

Private Delegate Sub AppendTextBoxDelegate(ByVal TB As TextBox, ByVal txt As String)

Private Sub AppendTextBox(ByVal TB As TextBox, ByVal txt As String)
    If TB.InvokeRequired Then
        TB.Invoke(New AppendTextBoxDelegate(AddressOf AppendTextBox), New Object() {TB, txt})
    Else
        TB.AppendText(txt)
    End If
End Sub

这是一个使用匿名委托的更新简化版本:

Here's an updated, simplified version that uses an anonymous delegate:

Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)
    Dim filename As String = System.IO.Path.Combine(TextBox2.Text, e.Name)
    Try
        My.Computer.FileSystem.CopyFile(e.FullPath, filename, True)

        TextBox3.Invoke(Sub()
                            TextBox3.AppendText("[New Text]")
                        End Sub)

    Catch ex As Exception
        Dim msg As String = "Source: " & e.FullPath & Environment.NewLine &
            "Destination: " & filename & Environment.NewLine & Environment.NewLine &
            "Exception: " & ex.ToString()
        MessageBox.Show(msg, "Error Copying File")
    End Try
End Sub

这篇关于在 Visual Basic 中跨线程时正确更新文本框(V​​S 2012 V11)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆