我是Visual Basic的新手,也是一般新编码的新手。 目前我正在使用一个使用filewatcher的程序。但如果我试试这个:
Public Class Form1
Private WithEvents fsw As IO.FileSystemWatcher
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
fsw = New IO.FileSystemWatcher("PATH")
fsw.EnableRaisingEvents = True
' fsw.Filter = "*.settings"
End Sub
Private Sub GetSettingsFromFile()
Some Code
More Code
CheckBox1.Checked = True
End Sub
Private Sub fsw_Changed(sender As Object, e As FileSystemEventArgs) Handles fsw.Changed
fsw.EnableRaisingEvents = False 'this is set because the file is changed many times in rapid succesion so I need to stop the Filewatcher from going of 200x (anyone has a better idea to do this?)
Threading.Thread.Sleep(100)
GetSettingsFromFile()
fsw.EnableRaisingEvents = True 'enabling it again
End Sub
End Class
但是当我这样做(尝试更改表单中的任何内容)时,我收到此错误: System.InvalidOperationException(WinForms.IllegalCrossThreadCall) 它不会阻止程序工作,但我想了解这里有什么问题以及为什么调试器会向我抛出这个 问候
答案 0 :(得分:0)
该事件正在辅助线程上引发。必须在UI线程上对UI进行任何更改。您需要封送对UI线程的方法调用并在那里更新UI。关于如何做到这一点的大量信息。这是一个例子:
Private Sub UpdateCheckBox1(checked As Boolean)
If CheckBox1.InvokeRequired Then
'We are on a secondary thread so marshal a method call to the UI thread.
CheckBox1.Invoke(New Action(Of Boolean)(AddressOf UpdateCheckBox1), checked)
Else
'We are on the UI thread so update the control.
CheckBox1.Checked = checked
End If
End Sub
现在,无论您身在何处,无论您使用什么线程,都可以直接调用该方法。如果您已经在UI线程上,则控件将被更新。如果你在辅助线程上,那么该方法将第二次调用自己,这次是在UI线程上,控件将在第二次调用时更新。